Skip to content

feat(metrics): emit a deadline-driven required-replicas gauge for KEDA - #526

Open
sohom-cs wants to merge 6 commits into
llm-d:mainfrom
sohom-cs:feat/deadline-required-replicas
Open

sohom-cs wants to merge 6 commits into
llm-d:mainfrom
sohom-cs:feat/deadline-required-replicas

Conversation

@sohom-cs

@sohom-cs sohom-cs commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds the deadline-driven required-replicas gauge from #465, llm_d_async_async_deadline_required_replicas, and the per-queue deadline_scaling settings it reads.

  • deadline_scaling on a queue: throughput_rps (R), cold_start_seconds (C), max_replicas, optional safety_factor (s, in (0, 1], default 1). Checked when the config loads and, for redis-sortedset, on a queues-file reload. No block, no gauge.
  • Each backlog poll computes, for a queue with the block, the maximum over bucket boundaries t > 0 of B(t) / (R · (t − C) · s), rounded up and capped at max_replicas. B(t) leaves out expired items. Items due within C pin it to max_replicas; a queue with nothing still due gives 0. The math is a pure function in pkg/deadlinescaling.
  • It runs in pollBacklog next to SetDeadlineProximity, from the same cumulative counts. Since Add sql transport backed by Postgres #452 the sql transport fills those counts too, so both redis-sortedset and sql get the gauge; Pub/Sub reports none and gets none.
  • Flows expose a queue's settings through a DeadlineScaling(queueID) method. pipeline.QueueBacklogStat gets ExpiringCountsFailed: a failed deadline read zeroes the counts, which would otherwise read as an empty queue, so the gauge drops its series for that poll; KEDA reads a missing series as 0 unless the trigger sets ignoreNullValues: "false".
  • The series goes with the queue's other snapshots in RemoveQueueSnapshots, and when a reload drops the block. The gauge carries only queue_id and queue_name and is marked experimental. A row in docs/observability.md describes it, and docs/deadline-scaling.md covers the settings, the computation and a KEDA trigger.

The gauge is per queue, so it is right only when each queue has its own deployment; the docs say so, and to aggregate processor replicas with max(). The per-pool gauge is #538, stacked on this one.

Why is this change needed?

KEDA's Prometheus scaler can't combine the deadline histogram with the throughput and cold-start constants, and recording rules scatter those constants away from the data (#465). This is the M3 signal in llm-d/llm-d-autoscaling#1572.

How was this tested?

  • Unit tests added/updated
  • Integration/e2e tests added/updated
  • Manual testing performed

Table tests for the computation and the config validation; poll-loop tests with a fake reporter for when the series is set, dropped and removed.

  • go vet and go test -race on pkg/deadlinescaling, pkg/metrics, pkg/redis, pkg/sqlflow, pkg/server: pass. make test passes; make lint passes (Go 1.26.0, Darwin arm64).
  • Not run: a KEDA ScaledObject against the gauge (planned with the M3 example in llm-d-autoscaling).

Checklist

  • Commits are signed off (git commit -s) per DCO
  • Code follows project contributing guidelines
  • Tests pass locally (make test)
  • Linters pass (make lint)
  • Documentation updated (if applicable)

Related Issues

Part of #465

Release note

Adds `llm_d_async_async_deadline_required_replicas`, an experimental per-queue gauge of the replicas needed to finish queued items before their deadlines, for use as a KEDA trigger. It is computed each backlog poll from the deadline-proximity counts and a new optional per-queue `deadline_scaling` block (`throughput_rps`, `cold_start_seconds`, `max_replicas`, `safety_factor`) on the `redis-sortedset` and `sql` transports. Expired items don't count, and a failed deadline read drops the queue's series.

Add a per-queue deadline_scaling block (throughput_rps, cold_start_seconds,
max_replicas, optional safety_factor) and the gauge
llm_d_async_async_deadline_required_replicas. Each backlog poll computes it
next to the deadline-proximity snapshot, from the same cumulative counts:
the maximum over bucket boundaries t with queued items of
B(t) / (R * (t - C) * safety_factor), rounded up and capped at
max_replicas; items due at or before the cold start pin it to
max_replicas. Both the redis-sortedset and sql transports report those
counts, so both get the gauge; flows expose a queue's settings through a
DeadlineScaling method, and the pipeline module does not change.

Fixes llm-d#465

Signed-off-by: Sohom Chakraborty <16609933+sohom-cs@users.noreply.github.com>
Signed-off-by: Sohom Chakraborty <16609933+sohom-cs@users.noreply.github.com>
@sohom-cs
sohom-cs requested a review from shimib as a code owner November 3, 2026 00:43
sohom-cs added a commit to sohom-cs/llm-d-async that referenced this pull request Nov 3, 2026
Signed-off-by: Sohom Chakraborty <16609933+sohom-cs@users.noreply.github.com>
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Unsigned commits detected! Please sign your commits.

For instructions on how to set up GPG/SSH signing and verify your commits, please see GitHub Documentation.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T00:53:10.580563Z b4d5ba7 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b4d5ba7fa2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread pkg/deadlinescaling/deadlinescaling.go Outdated
need = math.Max(need, float64(cumulative[i])/(c.ThroughputRPS*budget))
}
// Absorb float error so that exactly n replicas' worth is not rounded to n+1.
return min(int(math.Ceil(need-1e-9)), c.MaxReplicas)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve positive demand when applying the rounding tolerance

With one item in the 24-hour bucket and an accepted configuration of ThroughputRPS: 20000, ColdStartSeconds: 0, and MaxReplicas: 10, the computed demand is approximately 5.79e-10. Subtracting 1e-9 makes it negative, so this returns 0 instead of the required ceiling of 1; I reproduced this against the unchanged function. With scale-to-zero enabled, the advertised KEDA trigger can therefore keep workers at zero despite queued work. Handle positive demand separately from the empty-queue case so the rounding tolerance cannot erase the last required replica.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4321eb8: a positive demand now returns at least 1, so the tolerance can't round the last replica away. Your example (one item at 24h, 20000 rps) is a test case now.

Comment thread pkg/deadlinescaling/deadlinescaling.go Outdated
need = math.Max(need, float64(cumulative[i])/(c.ThroughputRPS*budget))
}
// Absorb float error so that exactly n replicas' worth is not rounded to n+1.
return min(int(math.Ceil(need-1e-9)), c.MaxReplicas)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply the replica cap before converting demand to int

For accepted settings that produce demand beyond the platform's integer range, the conversion happens before the cap can protect it. For example, ThroughputRPS: 1, SafetyFactor: 1e-20, and MaxReplicas: 10 with one item in the one-second bucket passes validation but returns -9223372036854775808 on the inspected linux/amd64 environment instead of 10. The poller then publishes that negative value as the required-replicas gauge. Bound the floating-point demand by MaxReplicas before converting it to int, including when the division produces positive infinity.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4321eb8: the demand is compared with max_replicas before the conversion, so values past the int range and +Inf return max_replicas. Your example and a +Inf case are test cases now.

Compare the demand with max_replicas while it is still a float: a tiny
throughput_rps or safety_factor can push it past the int range or to
+Inf, and the conversion then gave -9223372036854775808 on linux/amd64.
Also return at least 1 for any positive demand, so the 1e-9 rounding
tolerance can no longer turn queued work into 0 replicas.

Signed-off-by: Sohom Chakraborty <16609933+sohom-cs@users.noreply.github.com>
@sohom-cs
sohom-cs force-pushed the feat/deadline-required-replicas branch from 93a5d2f to 4321eb8 Compare November 3, 2026 21:41
@jtechapps jtechapps self-assigned this Nov 3, 2026
@jtechapps

Copy link
Copy Markdown
Collaborator

Expired items (le="0") pin the gauge to max_replicas, as the issue reads (t = 0 ≤ C). If late work shouldn't drive scaling, skipping that bucket is one line.

Late work shouldn't drive scaling decisions.

Per queue, as the issue asks. Queues that share one deployment would need their counts summed before the division; summing per-queue gauges in KEDA over-counts. A per-pool series can follow if you want it.

This is important. The metric labels should also changed so that aggregating metric over worker pool does not overcount.

A failed backlog read zeroes the counts, as it does for the proximity snapshot, so the gauge reads 0 for that poll. For an autoscaler, dropping the series instead, so KEDA's fallback applies, may be the safer choice. Which do you prefer?

drop the series.

Comment thread pkg/server/runner.go Outdated
metrics.SetDeadlineProximity(s.QueueID, s.QueueName, s.PoolName, counts)
if scaling != nil {
if cfg, ok := scaling.DeadlineScaling(s.QueueID); ok {
metrics.SetDeadlineRequiredReplicas(s.QueueID, s.QueueName, s.PoolName, cfg.RequiredReplicas(buckets, counts))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to separate out required replicas for queue and worker pool. Otherwise aggregating the metrics together will overcount replicas.

The main use-case is actually scaling based on backlog of all queues for a single worker pool which would map to an llm-d InferencePool. Typically you would have one worker pool per inference pool/model.

The worker pool deadline replicas is more important than queue level.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added more detailed comment here #526 (comment)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#538, stacked on this PR, is that split: llm_d_async_async_pool_deadline_required_replicas carries only pool_name, reads a deadline_scaling block on the worker pool (a queue's own throughput_rps overrides the pool's), sums each queue's due work per bucket before the one division, and drops the pool's series when any of its queues fails the deadline read. The per-queue gauge here stays for a queue with its own deployment, and #538's docs point queues that share one to the pool gauge, with max() across processor replicas. Not covered: it groups by pool_name, so two worker pools feeding one deployment would still undercount; a scaling_group key can follow if that setup is supported.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

metrics.SetDeadlineRequiredReplicas(s.QueueID, s.QueueName, s.PoolName, cfg.RequiredReplicas(buckets, counts)) still configures pool name in the metric which gives the impression that aggregating it by pool will work.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 58880fd: pollBacklog no longer passes s.PoolName, and the gauge carries only queue_id and queue_name. The per-pool number is #538's gauge.

@jtechapps

Copy link
Copy Markdown
Collaborator

On open question 2 (queues that share one deployment): neither of the two easy KEDA queries over the per-queue gauge gives the right number.

Why neither sum() nor max() of the per-queue gauges works

For one queue, the formula takes the worst case over horizons t:

need = maxₜ B(t) / (R · (t − C) · s)

When queues share a deployment, the replicas are shared, so the work has to be added up before taking that worst case:

need_pool = maxₜ [ Σ_q B_q(t) / R_q ] / ((t − C) · s)

Query Result Why
sum() of per-queue gauges Over-counts Adding each queue's worst case is at least the worst case of the total, and is larger when queues peak at different horizons. Each queue also rounds up separately, which can add up to 1 replica per queue.
max() of per-queue gauges Under-counts It ignores the work in every queue except one.

Two examples, with R=1, C=60s and s=1:

  • Queues peak at different horizons: Q1 has 100 items due in 2m, which needs 100/60 → 2 replicas. Q2 has 600 items due in 30m, which needs 600/1740 → 1. sum() gives 3, but the combined calculation gives max(100/60, 700/1740) → 2.
  • Queues peak at the same horizon: Q1 and Q2 each have 100 items due in 2m, so each needs 2. max() gives 2, but the combined calculation gives 200/60 → 4.

Suggested approach: one gauge per pool, computed inside the processor

  1. Move the deployment settings to the pool. cold_start_seconds, max_replicas and safety_factor describe the deployment being scaled, not a queue. If two queues on one deployment had different max_replicas values, it's unclear which one should apply. Put a deadline_scaling block on the worker pool config, next to gate_type/gate_params. Keep throughput_rps on the pool with an optional per-queue override, because queues with different request sizes finish items at different rates.

  2. Total the work per bucket across the pool's queues, then divide once. In pollBacklog:

    // work[i] is replica-seconds of queued work due within boundaries[i],
    // summed across the pool's queues.
    work[pool][i] += float64(counts[i]) / queueRPS

    After the loop, compute maxᵢ work[i] / ((tᵢ − C) · s) per pool, apply the cap and the cold-start check, and set a gauge labelled by pool_name only. That matches the repo's other pool-level gauges, like async_pool_worker_limit. This means changing RequiredReplicas to take work per bucket instead of raw counts. It stays a pure function, and the single-queue case is a pool with one queue.

  3. If any queue's read fails, drop the whole pool's series. A partial total would undercount. This ties into open question 3: dropping the series on a failed read, rather than zeroing it, lets KEDA's fallback apply.

  4. Use max() in the KEDA query. Every processor replica reads the same shared backlog and publishes the same gauge, so a sum() across processor pods multiplies the value by the number of pods. The docs example should say to aggregate with max().

One caveat about what "pool" means. pool_name is the async worker pool, but what KEDA scales is the inference deployment behind a queue's IGW URL. Usually they match one to one. If two worker pools send traffic to the same deployment, totalling by worker pool still undercounts. If that setup is supported, the grouping key should be an explicit scaling_group name rather than pool_name.

Since the description says either choice is easy to flip, this could be a follow-up rather than blocking this PR. If so, the docs for the per-queue gauge should say it's only correct when each queue has its own deployment.

Review on llm-d#526: late work shouldn't drive scaling, and a failed backlog
read should drop the required-replicas series so KEDA's fallback applies
instead of reading 0. QueueBacklogStat gets ExpiringCountsFailed, since
zeroed counts look like an empty queue. The docs say the per-queue value
is right only when each queue has its own deployment, and to aggregate
processor replicas with max().

Signed-off-by: Sohom Chakraborty <16609933+sohom-cs@users.noreply.github.com>
@sohom-cs

sohom-cs commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

All three are in 4dac828.

  1. Expired items no longer count. The bucket counts are cumulative, so they come out of every horizon, not only le="0".
  2. Agreed on one gauge per pool, as you laid it out; I'll do it in the next PR. Until then the docs say the per-queue value is right only when each queue has its own deployment, and to aggregate processor replicas with max().
  3. A failed read drops the series. Zeroed counts look like an empty queue, so QueueBacklogStat gets ExpiringCountsFailed, set where the redis-sortedset and sql flows zero the counts.

The description now says "Part of #465".

@jtechapps jtechapps mentioned this pull request Nov 16, 2026
19 of 30 tasks
@jtechapps jtechapps added this to the v1.1.0 milestone Nov 16, 2026
@sohom-cs

Copy link
Copy Markdown
Contributor Author

@jtechapps could you take another look now that your 11-05 points are addressed here and the per-pool gauge you laid out is #538, stacked on this one?

Comment thread docs/observability.md Outdated
| `llm_d_async_async_inference_latency_time_millis` | Histogram | Time in milliseconds spent calling `llm-d-router` (or other inference gateway), measured around each request attempt. Isolates "model time" from "queue time". Always registered. |
| `llm_d_async_async_queue_residence_time_millis` | Histogram | Time in milliseconds a message spent buffered in-process, from broker ingestion until a worker pulled it for processing. Measures the async delay introduced by the system (queue time). Always registered. |
| `llm_d_async_async_deadline_proximity_millis` | Histogram | Snapshot histogram of time in milliseconds remaining until each queued item's deadline, rebuilt once per backlog poll from exact cumulative `ZCOUNT` counts per bucket (`le="0"` holds items past their deadline but still queued; higher buckets are cumulative, so every item counts in each bucket it expires in). Redis sorted-set only; Cloud Pub/Sub cannot expose per-item deadlines. Because each poll replaces the snapshot, the series is not monotonic — `rate()` is meaningless; use `histogram_quantile` per scrape. The `_sum` is estimated from bucket midpoints. |
| `llm_d_async_async_deadline_required_replicas` | Gauge | Replicas a queue needs to finish its queued items before their deadlines, recomputed each backlog poll from the deadline-proximity counts and the queue's `deadline_scaling` settings (`throughput_rps` R, `cold_start_seconds` C, `max_replicas`, optional `safety_factor` s): the maximum over bucket boundaries t > 0 of B(t) / (R · (t − C) · s), where B(t) counts the items due within t that haven't expired, rounded up and capped at `max_replicas`. Expired items don't count; items due within C pin it to `max_replicas`. A failed deadline read drops the series for that poll, so KEDA's `fallback` applies. Only queues with `deadline_scaling`, on `redis-sortedset` and `sql`. The value is per queue, so it is right only when each queue has its own deployment: summing queues that share one over-counts. Every processor replica publishes the same value, so aggregate across them with `max()`. Meant as a KEDA trigger with threshold 1. |

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you make this metric description less verbose.

  1. something like "Replicas a queue needs to finish its queued items before their deadlines, recomputed each backlog poll from the deadline-proximity counts and the queue's deadline_scaling settings. The value is per queue, so it is right only when each queue has its own deployment: summing queues that share one over-counts. Every processor replica publishes the same value, so aggregate across them with max(). Meant as a KEDA trigger with threshold 1.
  2. there should be a new markdown file in the docs/ that goes into more detail of configuring the deadline_scaling configuration and be linked from the other doc files.
  3. we should mark this as an experimental feature/metric.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 58880fd: the row is your text, marked experimental and noting that it carries only queue_id and queue_name, with a link to the new docs/deadline-scaling.md (the settings, how the value is computed, and a KEDA trigger with ignoreNullValues: "false", since KEDA otherwise reads a dropped series as 0). The transports page and the README link to it too, and the metric's help text and the release note say experimental as well.

Comment thread pkg/metrics/metrics.go Outdated
DeadlineRequiredReplicas = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Subsystem: SchedulerSubsystem, Name: "async_deadline_required_replicas",
Help: "Replicas needed to finish the queue's queued items before their deadlines, from the latest deadline-proximity snapshot and the queue's deadline_scaling settings: the maximum over horizons t of B(t) / (throughput_rps * (t - cold_start_seconds) * safety_factor), where B(t) leaves out expired items, rounded up and capped at max_replicas. Only set for queues with deadline_scaling, on brokers that expose per-item deadlines, and not after a failed deadline read.",
}, queueLabels)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead usingqueueLabels that includes pool label in set. Create a queueOnlyLabels which excludes the pool labels so that metric consumers aren't able to aggregate by pool.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 58880fd: the gauge uses a new queueOnlyLabels (queue_id, queue_name) instead of queueLabels, and its set and remove helpers take only those two values. A test in metrics_test.go checks the gauge's label set.

@jtechapps

Copy link
Copy Markdown
Collaborator

@sohom-cs when will you be able to address the latest feedback?

Review on llm-d#526: with pool_name on the per-queue gauge, a sum by pool
looks valid but over-counts replicas for queues that share a
deployment. The gauge now uses queueOnlyLabels (queue_id, queue_name),
and the backlog poller no longer passes the pool name.

docs/deadline-scaling.md covers the deadline_scaling settings, how the
value is computed and a KEDA trigger, and is linked from the
observability and transports docs and the README. It also notes that
KEDA reads a missing series as 0 unless the trigger sets
ignoreNullValues to "false". The observability row is shorter, and the
docs, the metric's help text and the release note mark the feature
experimental.

Signed-off-by: Sohom Chakraborty <16609933+sohom-cs@users.noreply.github.com>
@sohom-cs
sohom-cs requested a review from wseaton as a code owner November 25, 2026 19:16
@jtechapps

Copy link
Copy Markdown
Collaborator

Thanks — 58880fd addresses my comments. LGTM once rebased (only a one-line README conflict with the multi-replica guide link; keep both). Two small nits, non-blocking: an explicit "safety_factor": 0 passes validation and acts as 1 while the error/docs say (0, 1] — either reject it or document "0 or omitted means 1"; and the deadline_proximity_millis row in observability.md still says "Redis sorted-set only" though sql fills it now.

README.md conflicted on the documentation list: main added the
multi-replica guide where this branch added the deadline scaling page.
Both entries are kept.

Also the two review nits on llm-d#526:
- An explicit safety_factor of 0 passes validation and means 1, as an
  omitted one does. The validation error and docs/deadline-scaling.md
  now say so, instead of only "(0, 1]".
- The deadline proximity row in docs/observability.md said Redis
  sorted-set only, but the sql transport fills those counts too.

Signed-off-by: Sohom Chakraborty <16609933+sohom-cs@users.noreply.github.com>
@sohom-cs

Copy link
Copy Markdown
Contributor Author

Merged main in 26cb9a4, keeping both README links. The same commit has both nits: the validation error and docs/deadline-scaling.md now say that a safety_factor of 0 or omitted means 1 (rejecting 0 would need a pointer field to tell it from omitted), and the deadline_proximity_millis row lists sql next to redis-sortedset.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants