Zylos
2026-12-05

Startup Readiness Deadlines Under Load: Fixed Timeouts vs Progress-Based Deadlines for Slow-Starting Agent Runtimes

researchai-agentssupervisorstartup-probestimeoutssystemdkubernetesreliabilityretry-stormtmux

Executive Summary

A supervisor that launches an agent CLI in a terminal session usually has one rule for startup: if the runtime has not reported READY within N seconds, kill it and start again. On an idle machine that rule is harmless. On a busy machine it is a cliff. Startup work is CPU-bound and shared, so adding concurrent cold starts stretches every one of them at the same time. Once the stretched start time crosses N, every attempt is killed just before it would have finished, all progress is thrown away, and the restarts add the same load again.

What the sources show:

  • Mature systems split "is it starting" from "is it still alive." Kubernetes added startupProbe because a liveness probe could not be both patient during startup and fast afterward. Its design proposal says that raising initialDelaySeconds "delays deadlock detection if the container starts faster than initialDelaySeconds" and that "there is no feedback loop on the actual startup time of the container." ECS has startPeriod and a service grace period; Nomad has separate healthy_deadline and progress_deadline.
  • systemd has the closest precedent for progress-based deadlines. TimeoutStartSec= is the fixed deadline (90 s by default in the system manager; Type=oneshot services have none by default). A Type=notify service may send EXTEND_TIMEOUT_USEC=... before it expires and then keep sending it; each message moves the deadline to at least now plus the interval, and startup continues until READY=1. Missing a repeat means the timeout fires. MariaDB and Elasticsearch both adopted it for slow crash recovery or metadata upgrades.
  • A heartbeat is not progress. Elasticsearch's implementation sends the extension from a fixed-delay timer whose callback never looks at startup state. That proves the process is scheduled, not that startup is advancing. A progress-based deadline is only as good as the signal feeding it.
  • Configurability helps but does not adapt. A single configured number is wrong on either the idle laptop or the crowded server. Kubernetes is revisiting its own CrashLoopBackOff defaults, which its design document calls "too conservative" for some workloads.
  • The amplification loop has a name and known controls. The metastable-failure literature identifies retries as a typical sustaining effect. The standard controls are randomized exponential backoff, retry budgets and limiting concurrency (Google SRE book, AWS Builders' Library).
  • In a toy model I ran (script in section 1.2), limiting concurrent starts and progress-based extension both removed all kills. At 32 sessions on 4 cores, a fixed 30 s deadline with immediate restart never got a single session ready in 900 simulated seconds (960 kills, every seed). Full-jitter backoff got all 32 ready after 254–282 s with 134–159 kills. A cap of 4 concurrent starts needed 64–70 s and no kills. Progress-based extension needed 62–66 s and no kills.

Recommendation in one paragraph: make progress the primary signal (observable activity from the runtime's process and terminal), treat a stall window with no progress as the real deadline, keep a configurable value only as the fallback for runtimes that emit no usable signal, put a hard ceiling on each admitted start, judge every event by its own timestamp on a monotonic clock so a late READY cannot revive an expired window, cap concurrent cold starts, restart with jittered backoff and a retry budget, and record every start duration, including the killed ones.

Evidence labels: Verified means read in the cited source. Simulated means I ran my own toy model, published in section 1.2. Inference is my reasoning from the sources.

1. The Problem: A Fixed Deadline Is a Cliff, Not a Margin

1.1 Why the start time is not a constant

A fixed deadline assumes startup time is a property of the program. For an agent CLI it is a property of the program plus the machine's current load. Node-style runtimes load and compile code, read configuration and history, spawn helper processes, and may talk to a network service before reporting ready. Most of that is CPU and disk work. When several sessions cold-start at once on a machine with few cores, each gets a fraction of a core.

Google's SRE book makes the same observation about services: "Processes are often slower at responding to requests immediately after starting than they will be in steady state" (SRE book, cascading failures). Startup time under contention is a distribution with a long right tail, and the tail moves with load.

A fixed deadline cuts that distribution at one point. Anything slower is declared dead, regardless of whether it was seconds from finishing.

1.2 The kill-and-restart amplification loop

The loop has four steps:

  1. A burst of sessions starts (boot, supervisor restart, upgrade, a user opening several sessions).
  2. Concurrency stretches each start. Some cross the deadline and are killed.
  3. The killed sessions restart from zero. Their earlier work is wasted, so the machine does more total work than if it had left them alone.
  4. The extra load stretches the others further. More cross the deadline.

The trigger (the initial burst) can disappear while the loop keeps going. The metastable-failure literature calls this a sustaining effect: a feedback loop that keeps the system in a bad state after the trigger is gone. The HotOS 2021 paper defines metastable failures as ones where "a trigger causes the system to enter a bad state that persists even when the trigger is removed," and argues the sustaining effect, not the trigger, is the root cause (Bronson et al.). A follow-up study of public incident reports presents "an in-depth study of 22 metastable failures from 11 different organizations" (Huang et al., OSDI 2022). A supervisor that restarts on a timeout is a retry mechanism, so it can be the sustaining effect.

The SRE book describes the same pattern for health checks: when a scheduler restarts tasks that fail a check, "health-checking itself" can make the service unhealthy, and temporarily disabling health checks "may permit the system to stabilize." Kubernetes' own probe page warns that liveness probes implemented badly "can lead to cascading failures," including "restarting of container under high load" (Kubernetes: probes).

Simulated. To see the shape of the cliff, I wrote a small model. It is a model of the mechanism, not a measurement of any runtime. Assumptions: 4 cores shared evenly among running starts; each session needs 6 to 10 CPU-seconds of work (uniform, drawn once per seed; a restart redoes the same work); time advances in 0.1 s ticks; an attempt that completes in the same tick as its deadline counts as ready; otherwise it is killed when its age reaches the deadline (age ≥ 30 s); the run stops at 900 s and events at exactly 900 s count. Policies:

  • Fixed: kill at 30 s, restart immediately.
  • Fixed + jitter: kill at 30 s, restart after full-jitter exponential backoff, a delay drawn uniformly from 0 to min(60, 5 × 2^(k−1)) s, where k is that session's kill count.
  • Admission: at most 4 concurrent starts, admitted first in, first out; the 30 s clock starts when a start is admitted, and a killed start rejoins the back of the queue.
  • Progress: the deadline moves out by 30 s whenever the attempt is advancing. In this model every running attempt is always advancing and nothing hangs, so only the 300 s ceiling could fire, and it never does.

Results over seeds 1–5 (ranges; "last ready" is when the last session of the burst became ready):

  • 12 sessions: every policy finishes with no kills. The last session is ready at 24–26 s (25–27 s with admission).
  • 16 sessions: fixed finishes at 40–59 s with 4–13 kills, and fixed + jitter at 44–60 s with the same kills. Admission needs 34–36 s and progress-based 31–34 s, both with no kills.
  • 20 sessions: fixed never gets a session ready (600 kills on every seed). Fixed + jitter finishes at 89–127 s with 31–45 kills. Admission needs 42–45 s and progress-based 39–42 s, with no kills.
  • 32 sessions: fixed never gets a session ready (960 kills on every seed). Fixed + jitter finishes at 254–282 s with 134–159 kills. Admission needs 64–70 s and progress-based 62–66 s, with no kills.

Four things stand out:

  • The cliff is sharp. Twelve sessions are fine and sixteen are not, because total work crosses cores times deadline (here 4 × 30 = 120 CPU-seconds; sixteen sessions need about 128).
  • Past the cliff, a fixed deadline with immediate restart degrades sharply, and from 20 sessions on it livelocks: no session ever becomes ready. Twenty sessions sit exactly on the edge. Sharing 4 cores, each attempt gets exactly 6.0 CPU-seconds before the 30 s kill, slightly less than the smallest start needs, so every attempt dies and restarts in lockstep. That result depends on the edge. With the kill rule changed to age greater than 30 s on 1 s ticks, which gives each attempt one more second, 5 of 8 seeds recovered in 92–165 s and 3 never did.
  • Jittered backoff recovers because it thins out concurrency, but it spends minutes and many wasted attempts getting there.
  • Admission and progress-based extension reach roughly the same finish time, because the machine cannot do the burst's work faster than total work divided by cores (section 6). The difference is that nothing is wasted.

The whole model, which produced every number above (Python 3, standard library only):

import random, statistics

DT, CORES, DEADLINE, CEILING, HORIZON, K = 0.1, 4, 30.0, 300.0, 900.0, 4

def sim(n, policy, seed):
    rng = random.Random(seed)
    work = [rng.uniform(6, 10) for _ in range(n)]   # CPU-seconds; a restart redoes the same work
    rem, start, kills = work[:], [0] * n, [0] * n
    wake, ready, durations = {}, {}, []
    queue, running = list(range(n)), []             # FIFO; a killed session rejoins at the back
    limit = CEILING if policy == "progress" else DEADLINE   # progress: always advancing, so only the ceiling applies
    for step in range(int(HORIZON / DT)):           # last tick ends at t = 900 s; events at 900 s count
        for i in [i for i, w in wake.items() if w <= step]:
            del wake[i]; queue.append(i)
        while queue and (policy != "admission" or len(running) < K):
            i = queue.pop(0); running.append(i); start[i], rem[i] = step, work[i]
        share = min(1.0, CORES / len(running)) if running else 0.0
        for i in running[:]:
            rem[i] -= share * DT
            age = (step + 1 - start[i]) * DT        # the clock starts at admission
            if rem[i] <= 1e-9:                      # completion wins a tie with the deadline
                running.remove(i); ready[i] = (step + 1) * DT; durations.append(age)
            elif age >= limit - 1e-9:               # kill rule: age >= limit
                running.remove(i); kills[i] += 1
                if policy == "jitter":              # full jitter: U(0, min(60, 5 * 2^(k-1))), k = kills so far
                    wake[i] = step + 1 + int(rng.uniform(0, min(60, 5 * 2 ** (kills[i] - 1))) / DT)
                else:
                    queue.append(i)
        if len(ready) == n:
            break
    last = max(ready.values()) if len(ready) == n else None
    return last, sum(kills), statistics.median(durations) if durations else None

for n in (12, 16, 20, 32):
    for policy in ("fixed", "jitter", "admission", "progress"):
        runs = [sim(n, policy, seed) for seed in (1, 2, 3, 4, 5)]
        f = lambda x: "-" if x is None else f"{x:.0f}"
        print(f"{n} {policy}: last ready {' '.join(f(r[0]) for r in runs)}; kills {' '.join(str(r[1]) for r in runs)};"
              f" median ok attempt {' '.join(f(r[2]) for r in runs)}")

"Median ok attempt" is the median, over successful attempts only, of the wall-clock time from that attempt's admission to READY. Section 6 uses it.

2. How Mature Systems Separate "Starting" from "Alive"

The pattern is consistent: a separate, more generous rule for the startup phase, a stricter one afterward, and an explicit handoff when readiness is first reached.

  • Kubernetes. The startupProbe runs first, and liveness and readiness probes do not run until it succeeds. On failure the kubelet kills the container and the restart policy applies.
  • Docker / ECS container checks. During startPeriod, failures do not count toward retries, and a success ends it. The container is marked unhealthy once the retries are used up.
  • ECS service. healthCheckGracePeriodSeconds (default 0) is how long the scheduler ignores load balancer, VPC Lattice and container health checks after a task starts.
  • systemd. TimeoutStartSec=, optionally extended with EXTEND_TIMEOUT_USEC. On expiry the unit fails and is stopped; Restart= and the start limits decide what happens next.
  • Nomad. A per-allocation healthy_deadline (5 m) sits inside a deployment-wide progress_deadline (10 m), which resets on each healthy allocation or manual promotion. An allocation that misses its deadline is unhealthy; the deployment fails if none becomes healthy before the progress deadline.
  • Erlang/OTP. Child start is synchronous, and gen_server accepts an optional init timeout. On expiry the child is killed and the caller gets {error, timeout}; supervisor restart intensity applies.
  • gRPC. Each connection attempt gets at least 20 s, and backoff resets only when the server's SETTINGS frame arrives. Between attempts it uses exponential backoff with jitter.

2.1 Kubernetes: why startupProbe exists

The design proposal for startup probes (KEP-950) states the problem as: slow-starting containers "are either killed before being up, or could be left deadlocked during a very long time before being killed." Slow starts, it says, come from long initial data loading, heavy workloads, and underpowered or overloaded nodes. It evaluated the alternatives that a supervisor author would try first:

  • Raising initialDelaySeconds avoids early kills, but "it also delays deadlock detection if the container starts faster than initialDelaySeconds," and "there is no feedback loop on the actual startup time of the container."
  • Raising the liveness failureThreshold gives the container time and keeps a feedback loop, but "it prevents the container from being killed in a timely manner if it deadlocks or otherwise hangs after it has initially successfully come up."

The proposal is explicit about its limits: "This proposal does not address the issue of pod load affecting startup (or any other probe that may be delayed due to load)." The startup probe buys a bigger, separate budget. It does not make the budget load-aware. (KEP-950; stages: alpha in 1.16, beta in 1.18, stable in 1.20.)

The documented fix is a separate probe with "a failureThreshold * periodSeconds long enough to cover the worst case startup time" (for example 30 × 10 s = 300 s). "Once the startup probe has succeeded once, the liveness probe takes over to provide a fast response to container deadlocks. If the startup probe never succeeds, the container is killed after 300s and subject to the pod's restartPolicy" (Kubernetes task docs).

Note what this is and is not. It is a larger fixed budget for the startup phase and a clean handoff. It is not progress-based: the probe has no notion of whether the container is advancing. Kubernetes does use a progress-based deadline one level up. progressDeadlineSeconds (default 600) on a Deployment counts as progress things like new pods becoming ready or a ReplicaSet scaling up, and "Kubernetes takes no action on a stalled Deployment other than to report a status condition" (Deployments).

Also note the kubelet's restart delay: "an exponential back-off delay (10s, 20s, 40s, …), that is capped at five minutes," which resets after 10 minutes of running; its purpose is to prevent "the starvation of kubelet by a misbehaving container" (KEP-4603).

2.2 ECS and container health checks

The ECS container HealthCheck has startPeriod: "The optional grace period to provide containers time to bootstrap before failed health checks count towards the maximum number of retries." It is off by default and ranges from 0 to 300 s. "If a health check succeeds within the startPeriod, then the container is considered healthy and any subsequent failures count toward the maximum number of retries" (ECS HealthCheck). That success-ends-the-grace-period rule is the same handoff as Kubernetes'.

At the service level, healthCheckGracePeriodSeconds is "The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy Elastic Load Balancing, VPC Lattice, and container health checks after a task has first started." The default is 0, which only means that none of the configured checks are ignored. "If you do not use any of the health checks, then healthCheckGracePeriodSeconds is unused." The grace period is not full protection either: "If your service has more running tasks than desired, unhealthy tasks in the grace period might be stopped to reach the desired count" (ECS CreateService). For a slow starter behind a strict check, the zero default judges it from its first second (inference).

2.3 Nomad: a per-attempt deadline inside a progress deadline

Nomad's update block has healthy_deadline (default 5 minutes, "the deadline in which the allocation must be marked as healthy") and progress_deadline (default 10 minutes). The progress deadline "is reset whenever an allocation as part of the deployment transitions to a healthy state or when a deployment is manually promoted." A rollout that keeps producing healthy instances is allowed to run long; one that stops producing them fails (Nomad update block). That is progress-based extension at the aggregate level, with the per-attempt deadline still fixed.

2.4 Erlang/OTP: keep the start phase short and make slow work explicit

OTP supervisors treat starting a child as a synchronous operation: "Starting, restarting, and manually terminating children are synchronous operations," so the supervisor process "will be blocked while it is performing any of those operations," and "Child processes are responsible for keeping their start and shutdown phases as short as possible" (OTP supervisor principles).

For gen_server, start_link "does not return until Module:init/1 has returned or failed," and a {timeout, Timeout} start option bounds initialization; on expiry the process is killed and the caller gets {error, timeout}. A process with slow work can return {continue, Continue} from init, "which will invoke the Module:handle_continue/2 callback, before receiving any external message / request" (gen_server). The start handshake therefore completes before warm-up, and callers' requests wait in the mailbox until warm-up has run.

The design lesson (inference) is to define two readiness points and say which one the deadline guards. The startup handshake means the process is alive and accepting input. Serviceable readiness means warm-up is done and requests will be answered promptly. If READY means the handshake, the start deadline applies to a smaller, more predictable step. Warm-up then needs its own budget, or its own visible state, so that a session that accepts input but is still warming is not taken for a hung one.

OTP also bounds restarts rather than time: if more than intensity restarts occur within period seconds, "the supervisor terminates all the child processes and then itself," with defaults of 1 and 5 seconds (same page). The stated intention is "to prevent a situation where a process repeatedly dies for the same reason, only to be restarted again." A deadline kill under load is not the same reason as a crash, which matters for how kills are counted (section 7).

2.5 gRPC and Envoy: handshakes, floors and jitter

gRPC's connection backoff specification sets MIN_CONNECT_TIMEOUT = 20 seconds as a floor on each attempt and says an attempt's timeout is Max(current_deadline, now() + MIN_CONNECT_TIMEOUT), so backoff never shortens the time a single attempt is allowed. It uses INITIAL_BACKOFF = 1 second, MULTIPLIER = 1.6, MAX_BACKOFF = 120 seconds and JITTER = 0.2, and resets the backoff only "when the SETTINGS frame is received," because that is when "we know for sure that this connection was accepted by the server" (gRPC connection backoff). Two ideas carry over: a minimum per-attempt time that retry policy cannot erode, and resetting backoff on application-level readiness, not on process spawn.

Envoy's active health checker can delay its first check by "a random time in ms between 0 and initial_jitter" and add interval_jitter to every interval (Envoy health check proto). The documentation describes only the mechanism. The effect that matters here, that many checkers do not fire in lockstep, is my reading (inference).

3. Progress-Based Extension: systemd's EXTEND_TIMEOUT_USEC

3.1 The mechanism

Verified from the systemd manuals and source:

  • TimeoutStartSec= "Configures the time to wait for start-up." If a daemon "does not signal start-up completion within the configured time, the service will be considered failed" and shut down. infinity disables the timeout. It defaults to the manager's DefaultTimeoutStartSec= (90 s), "except when Type=oneshot is used, in which case the timeout is disabled by default" (systemd.service, systemd-system.conf).
  • A Type=notify service signals completion with READY=1 through sd_notify.
  • The same service may send EXTEND_TIMEOUT_USEC=.... "The first receipt of this message must occur before TimeoutStartSec= is exceeded." After that, startup may continue "provided the service repeats" the message "within the interval specified," until READY=1 arrives. The mechanism exists for runtime and stop timeouts too (systemd.service).
  • The value is "a time in microseconds during which the service must send a new message." A timeout occurs "if the message is not received," and only "if the runtime of the current state is beyond the original maximum times" (sd_notify).
  • How the deadline moves: the service manager computes the monotonic time now plus the requested interval, then "Extends the specified event source timer to at least the specified time, unless it is already later anyway" (src/core/service.c). Each message therefore sets the deadline to the later of the current deadline and now plus the interval. It does not add the interval to the old deadline, so sending more often does not bank extra time.
  • STATUS=... carries a free-form single-line status, with the example "Completed 66% of file system check…". WATCHDOG=1 is a separate keep-alive for the running phase.

Three properties of this design are worth copying:

  1. A base deadline remains. The first extension must arrive before the original timeout expires, so a service that never reports cannot extend anything.
  2. Extensions are leases, not grants. Each message moves the deadline to a short window ahead of the moment it was sent. Silence ends the lease. The deadline moves forward only as long as the process keeps proving it is working.
  3. Old managers ignore it. MariaDB's tracking issue notes that "The use of EXTEND_TIMEOUT_USEC= on older services has no effect and is therefore compatible," so adoption is low-risk (MDEV-14705).

3.2 How real projects used it

MariaDB's tracking issue started from a to-do list of slow phases and proposed sending the extension at twice InnoDB's 15-second progress-report interval. What shipped in 10.1.33, 10.2.15 and 10.3.6 added it to InnoDB and XtraDB. Redo log recovery already reported progress through sd_notifyf(). The buffer pool is covered at shutdown, not startup ("On startup I haven't included the buffer pool load because as I understand it it continues in the background while the server is processing queries"). Galera snapshot transfers were split off ("Please file a separate ticket for the Galera snapshot transfer") (MDEV-14705). The issue also records the cost: a follow-up bug titled "service_manager_extend_timeout() being called too often" (MDEV-17003), and later tickets for long Galera transfers. MariaDB's documentation says that with systemd 236 or later you should not need to override TimeoutStartSec manually even when crash recovery runs long (MariaDB docs).

Elasticsearch added it after users reported that "after an upgrade from Elasticsearch 7.3 to 7.4, systemd will kill the elasticsearch process before it finishes starting up" while the node was upgrading on-disk metadata (elastic/elasticsearch#49593). The fix says: "We do this by repeatedly sending EXTEND_TIMEOUT_USEC to extend the timeout by thirty seconds; we do this every fifteen seconds." Given systemd's rule above, a message that systemd receives at time r sets the deadline to the later of the current deadline and r + 30 s. Early messages leave the original deadline in force: with systemd's documented 90 s, a message received at 15 s leaves 75 s. Once the extensions overtake the base deadline and the messages arrive on schedule, the deadline stays 15–30 s ahead (inference from the two sources). The implementation calls threadPool.scheduleWithFixedDelay with a callback that only sends EXTEND_TIMEOUT_USEC=30000000 and logs a failed send. The task is cancelled in onNodeStarted after READY=1 (PR #49784 diff).

3.3 Heartbeat versus progress

The Elasticsearch implementation extends on a timer, and its callback does not check whether startup is advancing. That is a liveness heartbeat: it says the process (or one thread in it) is still running. A deadlocked startup with a healthy timer thread would extend forever, up to whatever other limit exists. MariaDB's approach is closer to progress (inference), because InnoDB's redo-log recovery already sent its systemd notifications from the progress-reporting code inside the slow phase. This is the central design question for a supervisor, which sees the runtime from outside:

  • Heartbeat answers "is the process alive?" It is cheap to emit and cheap to fake by accident.
  • Progress answers "is startup advancing?" It needs a signal that changes only when work happens.

Kubernetes' Deployment progressDeadlineSeconds and Nomad's progress_deadline define progress by discrete events (an instance became ready) rather than by a clock. Inside a single start, the analogous events are phase transitions or output.

3.4 What counts as a progress signal for an agent CLI

An external supervisor cannot call sd_notify on the runtime's behalf, but it can watch things that change only if work happens. These are candidates (inference; I did not measure which are reliable for any specific runtime):

  • Cumulative CPU time of the runtime's process tree, read from /proc/PID/stat, increasing.
  • New bytes appearing in the terminal pane or a startup log.
  • New child processes, file descriptors opened, or files touched.
  • Explicit phase events from the runtime or its hooks (for example "config loaded," "auth checked"). This is the most trustworthy signal when available, and it matches systemd's STATUS=.

All but the last are signs of activity, not proof of progress (inference). A busy loop keeps CPU time rising, and a runtime that prints the same retry line every few seconds keeps producing output. Either one renews the stall window indefinitely, which is why the hard ceiling must stay. The opposite error matters as much. A legitimate wait for the network, such as an authentication round trip, a model or plugin download, or a slow proxy, can show neither CPU nor output for longer than the stall window, and a healthy start gets killed. Ways to handle it, in order of preference:

  • Have the runtime announce a waiting phase ("waiting for auth," "downloading"), and give known waiting phases their own, longer stall window.
  • Count network activity of the process tree, such as bytes received, as progress while such a phase is open.
  • Keep the stall window comfortably above the longest healthy silent gap measured in section 6.

Combine at least two signals: CPU-time advance catches silent but busy starts, and output or phase events tell busy-looping from useful work. A start that shows nothing at all and has announced no wait is the case a stall window should kill.

4. Configurable Deadlines and Their Pitfalls

Making the deadline a setting is the cheapest change, and it is a reasonable fallback. It also has predictable failure modes.

  • One number for all conditions. Kubernetes' proposal set initialDelaySeconds aside partly because "there is no feedback loop on the actual startup time of the container." A static number tuned on a lightly loaded machine fails under burst; tuned for the worst case it delays failure detection for every genuinely broken start.
  • Large values silently remove detection. systemd accepts infinity for TimeoutStartSec=, and its manual tells you to pass it "to disable the timeout logic." A supervisor that lets an operator set a very large value must still keep a ceiling.
  • Defaults age badly. ECS's grace period defaults to 0, and systemd's 90 s default applies to every service that does not set its own, except Type=oneshot. Elasticsearch's PR names a sixty-second systemd default as the limit its startup could exceed. That figure is the PR's own: systemd documents 90 s, and Elasticsearch's packaged 7.5 unit sets no TimeoutStartSec. Either way, a default chosen for typical conditions became wrong after an upgrade changed the work done at start.
  • Config alone doesn't adapt to load. The same machine needs different values at 2 sessions and 30.
  • Retry knobs need the same care. KEP-4603 (alpha in Kubernetes 1.32) proposes a faster default restart curve, with an initial back-off of 1 s and a maximum of 1 minute. It notes that "the decay to 5 minute back-off delay, and the 10 minute recovery threshold, are considered too conservative" for pods that exit successfully or are expected to run under 10 minutes. A configurable maximum was split into a separate proposal, KEP-5593 (KEP-4603). Expect the same pressure on any supervisor's restart policy.

A sound role for the configurable value is the stall window and the ceiling (section 7), not a single "READY within N" number.

5. Admission Control and Staggering

Deadlines decide when to give up on one start. Admission control decides how many starts to attempt at once, which controls the load that makes starts slow.

Limit concurrent cold starts. The SRE book advises: "When adding load to a cluster, slowly increase the load." It notes that when the cache is completely empty, "100% of requests are costly." In the simulation (section 1.2), capping concurrent starts at the core count finished a 32-session burst in 64–70 s with zero kills. A fixed deadline with jittered backoff took 254–282 s and 134–159 kills. A start queue also makes the deadline meaningful again, provided the clock starts when a start is admitted, not when it is requested. The cost is that early sessions finish sooner and later ones wait, so queue position should be visible.

Back off with jitter, and budget retries. "If all the failed calls back off to the same time, they cause contention or overload again when they are retried," and "Jitter adds some amount of randomness to the backoff to spread the retries around in time" (AWS Builders' Library). The same source limits retries locally with a token bucket, which "allows all calls to retry as long as there are tokens, and then retry at a fixed rate when the tokens are exhausted." The SRE book recommends "randomized exponential backoff," limiting retries per request, and a server-wide budget, for example "only allow 60 retries per minute in a process," after which "don’t retry; just fail the request." For a supervisor, the equivalent is a per-machine budget of restarts per minute.

Use the OS restart-rate limits as a backstop, not a fix. systemd refuses starts after a burst: DefaultStartLimitIntervalSec= is 10 s and DefaultStartLimitBurst= is 5 (systemd-system.conf). The limits count every start: "they apply to all kinds of starts (including manual), not just those triggered by the Restart= logic." A timeout-kill loop trips them as fast as a crash loop. Units that reach the limit "are not attempted to be restarted anymore"; they "may still be restarted manually or from a timer or socket at a later point, after the interval has passed" (systemd.unit). The limit does not tell a slow start from a crash, and it ends in refusal. A supervisor of long-lived agent sessions probably wants to degrade instead of stop.

Give startup more resources, or less competition. GKE's CPU startup boost (a Preview feature) raises a pod's CPU request during initialization and scales it back afterward. It works "by temporarily increasing CPU requests during initialization and resizing them back to baseline levels in-place" (GKE how-to). In the startup phase "the application initializes using the temporarily elevated CPU allocation to avoid initialization throttling," and the boost is removed "after the Pod reaches the Ready status and the durationSeconds period has passed" (GKE VPA concepts). A single-host analogue is running startups at higher priority than idle sessions, or pausing optional work while cold starts are in flight (inference).

6. Choosing Numbers from Measured Distributions

The AWS Builders' Library gives a simple rule for timeouts: "we choose an acceptable rate of false timeouts (such as 0.1%)," then "look at the corresponding latency percentile" (p99.9 in the example). It warns that when p99.9 is close to p50, "adding some padding helps us avoid small latency increases that cause high numbers of timeouts." Applied to startup:

  1. Record every start as two durations. Queue wait runs from request to admission. Start time runs from admission to READY. Also record the context at admission (concurrent starts, load average, core count). The ceiling and stall window apply to start time only. Mixing in queue wait, or mixing idle and burst conditions, blurs the distribution.
  2. Record killed starts too, as right-censored. This is the trap in the method (inference). If a fixed deadline kills every start at 30 s, the observed start times never exceed 30 s, and the measured p99 looks reassuring. In the simulation at 16 sessions, the median successful attempt under the fixed deadline took 23–28 s (seeds 1–5). In the same bursts under progress-based extension, where nothing is killed, the median start took 27–32 s. The fixed policy's data simply lacks every start slower than 30 s. Log "killed at 30 s, not finished" so the tail is visible, and run measurement with the deadline relaxed.
  3. Group by load bucket (for example, concurrent starts 1, 2–4, 5–8, more) and compute percentiles per bucket. The ceiling should come from the heavy bucket's p99.9 plus padding.
  4. Size the stall window from gaps, not totals. Measure the time between consecutive progress signals during healthy starts, including known waiting phases. The stall window is a high percentile of that gap, plus padding. It is far shorter than the total start time and unaffected by queueing, so it can stay tight.
  5. Check the ceiling and the queue separately. Say a start needs about W CPU-seconds, the machine has C cores, admission allows k concurrent starts, and, as in section 1.2's model, one start uses at most one core. Each admitted start then takes about W × max(1, k / C), and that per-start time is what the ceiling must cover (with C = 4, k = 2 and W = 8, that is 8 s, not 4 s). A burst of N starts needs at least N × W / C to drain. That is a lower bound at full load, which partial batches and unequal W make slower. Example: 32 starts of 8 CPU-seconds on 4 cores, admitted 4 at a time. Each start takes about 8 s, well inside a 15 s ceiling, yet the burst still needs about 64 s, and the last session waits about 56 s in the queue. Without admission control (k = N), the per-start time becomes about N × W / C once N exceeds C. A ceiling below that for the largest burst you support cannot be met by construction.
  6. Re-measure after changes. A runtime upgrade that adds startup work (an index build, a migration) shifts the distribution, as the Elasticsearch case shows.

7. Recommended Design for Agent Supervisors

The structure combines section 2's separation, section 3's lease semantics and section 5's admission control. Items 1–5 are the deadline; 6–8 are the surrounding policy.

  1. Name the phases. The phases are QUEUED, STARTING, STOPPING and RUNNING. A start that failed waits in BACKOFF, or in HELD when the restart budget is empty. Each admission spawns a new attempt with its own id. READY is the single handoff from STARTING to RUNNING, after which liveness rules apply. Define READY as narrowly as the runtime allows (the handshake: alive and accepting input), and track warm-up separately (section 2.4).
  2. Progress signal is primary. The supervisor samples at a fixed period P (for example every few seconds). It treats the start as advancing if any chosen signal changed since the last sample: CPU time of the process tree, new output, or an explicit phase event. Prefer phase events when the runtime offers them.
  3. Stall window is the real deadline. Kill only when no progress has been seen for the stall window. This is systemd's lease: each sign of progress moves the deadline to that moment plus the window, and silence ends it. Seed the value from the gap distribution in section 6.
  4. Hard ceiling bounds everything. The time since admission never exceeds the ceiling, however much progress is seen. This guards against heartbeat-style false progress (section 3.3) and busy-loop hangs. Choose it from the heavy-load bucket's p99.9 of start time (admission to READY), not from the idle case.
  5. Configurable fallback. For runtimes with no usable signal, the stall window collapses to a fixed startup_timeout (the current behavior). It is now one setting among several, with documented defaults and a validated range. Kubernetes' startup probe and ECS's startPeriod show the same shape: a bounded budget during startup only.
  6. Admission control. Limit concurrent STARTING and STOPPING sessions to a small multiple of the core count (a dying process tree still uses CPU and may hold the pane), queue the rest first in, first out, and start each session's clocks at admission. Report "queued" separately from "starting" so a waiting session is not mistaken for a hung one.
  7. Restart policy that doesn't amplify. After a deadline kill or an early exit, restart with full-jitter exponential backoff. Every restart takes a token from a per-machine budget. Reset the backoff only on READY (as gRPC resets on the SETTINGS frame). Count deadline kills separately from crashes: OTP's intensity rule exists to stop a process that "repeatedly dies for the same reason," and a load-induced timeout is a different cause. When the budget is empty, hold the restart, pause new starts, and tell the owner once. While any restart is held, a new failure joins the back of the held queue instead of taking a token. When tokens return, release held restarts in the order they were held and resume admission. Re-arm the alert after the next READY.
  8. Make it observable. For every start, record request time, admission time, queue wait, start time to READY, which signal kept it alive, the load context, and the end reason ("stalled," "ceiling," "crashed"). Also record when the budget held a restart. Those records feed the percentiles in section 6.

The decision procedure, run on one monotonic clock:

# Every event carries the monotonic time it was observed (e.t) and the attempt id of the process
# tree that produced it (e.gen). Never use wall-clock time. GRACE and KILL_WAIT are multiples of P.
deadline(s) = min(s.last_progress + STALL, s.admitted_at + CEILING)

admit(s, now):        # FIFO; only while fewer than K sessions are STARTING or STOPPING and none is HELD
    s.gen += 1; s.stuck = false; spawn a process tree tagged with s.gen
    s.phase = STARTING; s.admitted_at = now; s.last_progress = now

tick(now):            # every P seconds
    for e in events with e.t <= now, in order of e.t:
        s = e.session
        if e.gen != s.gen or s.phase != STARTING or e.t >= deadline(s): drop e   # stale attempt or too late
        elif e is READY:    s.phase = RUNNING; s.failures = 0; alerted = false
        elif e is EXIT:     stop(s, "crashed", now)              # counted apart from deadline kills
        elif e is PROGRESS: s.last_progress = e.t
    for s in STARTING sessions with now >= deadline(s):
        stop(s, "ceiling" if s.admitted_at + CEILING <= s.last_progress + STALL else "stalled", now)
    for s in STOPPING sessions:       # the slot stays taken until the tree is empty or the owner frees it
        if no PIDs remain in s's process group or cgroup: fail(s, now)
        elif now >= s.stop_at + GRACE:
            signal the tree with KILL                                  # repeated each tick
            if now >= s.stop_at + GRACE + KILL_WAIT and not s.stuck: s.stuck = true; alert_owner(s)
    while a session is HELD and budget.take(now): move the oldest HELD session to BACKOFF (jittered delay)
    move BACKOFF sessions whose delay has passed to QUEUED; admit while allowed

stop(s, reason, now):
    s.phase = STOPPING; s.reason = reason; s.stop_at = now; signal the tree with TERM

fail(s, now):         # only once the tree is gone
    record(s, s.reason); s.failures += 1
    if no session is HELD and budget.take(now):
        s.phase = BACKOFF; s.due = now + uniform(0, min(CAP, BASE * 2^(s.failures - 1)))
    else: s.phase = HELD (at the back); if not alerted: alert_owner(); alerted = true

What the procedure pins down:

  • Event time, not processing time. An event counts only if it is stamped before the deadline in force at that moment. A READY or an output line stamped at or after the deadline is dropped, even when it is processed in the same tick that kills. A late READY therefore cannot revive an expired window, and late output cannot extend one. Applying events in timestamp order makes the outcome independent of arrival order within a tick.
  • Each delay is bounded separately. From real activity to its observation stamp: up to P for sampled signals (CPU time, pane polling), about 0 for events pushed and stamped on arrival. From that stamp to the logical deadline: exactly STALL. From the deadline to TERM: up to P, since TERM goes out at the first tick at or after the deadline, never early. Activity to TERM is therefore at most STALL + 2P for sampled signals and STALL + P for pushed ones. With P = 5 s and STALL = 32 s, activity at 1 s sampled at 5 s sets the deadline to 37 s and TERM goes out at 40 s: 39 s, within 42 s. Keep P well below STALL.
  • Attempts are not interchangeable. Events carry their attempt's id, so output or a READY from a killed attempt never counts for the next one.
  • A kill takes time. TERM, then KILL after GRACE; the slot frees only when no PIDs are left, so no restart runs beside a dying tree. A tree that dies holds its slot for at most deadline + P + GRACE, plus the reap time after KILL. If PIDs remain at stop + GRACE + KILL_WAIT (a process stuck in uninterruptible I/O, say), the session is marked stuck and the owner is alerted once for that attempt. KILL keeps being re-sent and the slot stays taken until no PIDs remain, which then calls fail(), or until the owner intervenes; freeing it sooner would bring the overlap back.
  • Crashes are not timeouts. An exit before READY stops the attempt at once as "crashed" (the rest of the tree is reaped first), instead of running into the stall window and being miscounted.

Test it with a fake clock rather than a real runtime. I transliterated the procedure into Python (a temporary script, not published) and replayed it against fourteen scenarios, and it handled all of them as intended:

  • Late READY: with a 300 s ceiling and 5 s ticks, a READY stamped at 302 s is dropped and the kill fires at 300 s (at 303 s with ticks offset by 3 s, still dropping that READY).
  • Late signals after a stall: a READY that arrives after a 30 s stall is dropped, and output stamped after the stall deadline cannot renew the window.
  • Real progress and real hangs: a slow start that keeps progressing reaches RUNNING. A silent hang is killed at the stall window, a heartbeat-only hang at the ceiling, and an early exit is recorded as a crash at the next tick.
  • Bursts and the budget: a burst of 10 starts with an admission limit of 4 and a 15 s ceiling queues without kills. When the budget runs out, restarts are held and one alert is sent; when tokens return, starts resume and reach READY, and the backoff resets.
  • Stale attempts and slow kills: a READY or output from a killed attempt is dropped, and a tree that ignores TERM gets KILL at GRACE and holds its slot until reaped.
  • Token order, stuck trees and delays: when one token returns in the tick a second session's tree empties, the session already held gets it. A tree that survives KILL raises one alert, keeps its slot, and nothing else is admitted until its PIDs go. The sampling example above sends TERM at 40 s.

A version without attempt ids or a STOPPING phase fails the two stale-and-slow-kill scenarios: it counts the stale READY, lets stale output stretch the new window from 60 s to 80 s, and admits a new start beside the dying tree. Without the held-first rule and KILL_WAIT, the fresh failure takes the token while the held session waits, and the stuck tree gets KILL every tick with no alert. A plainer skeleton (READY checked first, no event timestamps, ceiling from spawn) fails five of the first nine.

8. What I Could Not Confirm

  • I did not measure real agent CLI startup times, so the numbers in section 1.2 are from a model, and the progress signals in section 3.4 are candidates, not a validated set for any runtime. The fake-clock replay in section 7 checks the decision logic, not any real runtime.
  • The sixty-second systemd default that Elasticsearch's PR mentions does not match systemd's documented 90 s; I did not determine which distribution or configuration it reflects.
  • Kubernetes' restart back-off figures were read in KEP-4603, not on the Pod lifecycle page, whose relevant section was not retrievable in my fetch. The back-off defaults and the GKE startup CPU boost feature are also still changing between releases.
  • The ECS startPeriod bounds and defaults come from the API reference; I did not verify the console documentation.
  • The OSDI 2022 study of metastable failures is cited only for what its abstract says (22 failures from 11 organizations); I did not read the paper's treatment of retries.

Sources