feat(lambda): add init-timeout-seconds so a cold runtime gets its own init budget (#6442)

* feat(lambda): add init-timeout-seconds so a cold runtime gets its own init budget

* fix(lambda): count the init budget from container start, apply it only until the first /next poll, and cover it in SQS visibility

* test(lambda): check the dispatch wait directly instead of on the clock, and correct the init budget docs
This commit is contained in:
floverfelt authored and GitHub committed 2026-10-25 14:03:34 -04:00
1 parent 97de815256
commit 4d35617518
13 files changed
+205 -20

No files matched your search

@@ -3052,6 +3052,17 @@ public interface EmulatorConfig {
@WithDefault("300")
int containerIdleTimeoutSeconds();
/**
* Seconds a newly started runtime has to finish its init and request its first invocation,
* matching the 10 second Init phase AWS allows. A function whose Timeout is longer waits
* that long instead, as AWS re-runs a slow init inside the invoke. The function's Timeout
* itself starts when the invocation is dispatched.
*
* Env var: FLOCI_SERVICES_LAMBDA_INIT_TIMEOUT_SECONDS
*/
@WithDefault("10")
int initTimeoutSeconds();
/**
* One shutdown drain budget shared by provisioned and on-demand Lambda containers.
* Values outside 1 through 300 seconds fail initialization.
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.model.PendingInvocation;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
@@ -69,6 +70,7 @@ public class LambdaExecutorService implements Resettable {
private final Clock clock;
private final long asyncRetryDelayMs;
private final boolean dockerExecutor;
private final int initTimeoutSeconds;
/** Moved on by a reset so that retries still waiting from before it are dropped. */
private final AtomicLong generation = new AtomicLong();
private final Map<String, Long> deletions = new ConcurrentHashMap<>();
@@ -89,7 +91,8 @@ public class LambdaExecutorService implements Resettable {
EmulatorConfig config) {
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, lambdaServiceInstance, null, clock,
Duration.ofSeconds(config.services().lambda().asyncRetryDelaySeconds()),
!"kubernetes".equalsIgnoreCase(config.services().lambda().executor().trim()));
!"kubernetes".equalsIgnoreCase(config.services().lambda().executor().trim()),
config.services().lambda().initTimeoutSeconds());
}
LambdaExecutorService(WarmPool warmPool,
@@ -98,7 +101,7 @@ public class LambdaExecutorService implements Resettable {
AsyncInvokeDestinationRouter destinationRouter,
LambdaService directLambdaService) {
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService,
Clock.systemUTC(), Duration.ZERO, true);
Clock.systemUTC(), Duration.ZERO, true, 0);
}
LambdaExecutorService(WarmPool warmPool,
@@ -109,7 +112,7 @@ public class LambdaExecutorService implements Resettable {
Clock clock,
Duration asyncRetryDelay) {
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter, null, directLambdaService, clock,
asyncRetryDelay, true);
asyncRetryDelay, true, 0);
}
private LambdaExecutorService(WarmPool warmPool,
@@ -120,7 +123,8 @@ public class LambdaExecutorService implements Resettable {
LambdaService directLambdaService,
Clock clock,
Duration asyncRetryDelay,
boolean dockerExecutor) {
boolean dockerExecutor,
int initTimeoutSeconds) {
this.warmPool = warmPool;
this.objectMapper = objectMapper;
this.concurrencyLimiter = concurrencyLimiter;
@@ -130,6 +134,7 @@ public class LambdaExecutorService implements Resettable {
this.clock = clock;
this.asyncRetryDelayMs = asyncRetryDelay.toMillis();
this.dockerExecutor = dockerExecutor;
this.initTimeoutSeconds = initTimeoutSeconds;
}
/** Package-private constructor for testing without CDI, leaving destinations unrouted. */
@@ -137,7 +142,7 @@ public class LambdaExecutorService implements Resettable {
ObjectMapper objectMapper,
LambdaConcurrencyLimiter concurrencyLimiter) {
this(warmPool, objectMapper, concurrencyLimiter, null, (Instance<LambdaService>) null, null,
Clock.systemUTC(), Duration.ZERO, true);
Clock.systemUTC(), Duration.ZERO, true, 0);
}
LambdaExecutorService(WarmPool warmPool,
@@ -145,7 +150,15 @@ public class LambdaExecutorService implements Resettable {
LambdaConcurrencyLimiter concurrencyLimiter,
AsyncInvokeDestinationRouter destinationRouter) {
this(warmPool, objectMapper, concurrencyLimiter, destinationRouter,
(Instance<LambdaService>) null, null, Clock.systemUTC(), Duration.ZERO, true);
(Instance<LambdaService>) null, null, Clock.systemUTC(), Duration.ZERO, true, 0);
}
LambdaExecutorService(WarmPool warmPool,
ObjectMapper objectMapper,
LambdaConcurrencyLimiter concurrencyLimiter,
int initTimeoutSeconds) {
this(warmPool, objectMapper, concurrencyLimiter, null, (Instance<LambdaService>) null, null,
Clock.systemUTC(), Duration.ZERO, true, initTimeoutSeconds);
}
public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type) {
@@ -360,18 +373,21 @@ public class LambdaExecutorService implements Resettable {
buildErrorPayload(initFailureMessage(e, dockerExecutor), "Lambda.InitError"),
null, requestId);
}
long deadlineMs = System.currentTimeMillis() + (long) fn.getTimeout() * 1000;
PendingInvocation invocation = new PendingInvocation(
requestId, payload, deadlineMs, fn.getFunctionArn(),
new CompletableFuture<>());
invocation.setClientContext(clientContext);
RuntimeApiServer runtimeApiServer = handle.getRuntimeApiServer();
boolean initializing = !runtimeApiServer.hasRuntimePolled();
long dispatchWaitMs = dispatchWaitMs(fn.getTimeout(), initializing,
runtimeApiServer.getContainerStartedAtMs(), System.currentTimeMillis());
try {
long deadlineMs = System.currentTimeMillis() + (long) fn.getTimeout() * 1000;
PendingInvocation invocation = new PendingInvocation(
requestId, payload, deadlineMs, fn.getFunctionArn(),
new CompletableFuture<>());
invocation.setClientContext(clientContext);
handle.getRuntimeApiServer().enqueue(invocation);
runtimeApiServer.enqueue(invocation);
CompletableFuture.anyOf(
invocation.getDispatchedFuture(), invocation.getResultFuture())
.get(fn.getTimeout() + RUNTIME_DISPATCH_GRACE_SECONDS, TimeUnit.SECONDS);
.get(dispatchWaitMs, TimeUnit.MILLISECONDS);
InvokeResult result = invocation.getResultFuture().get();
warmPool.release(handle);
@@ -384,7 +400,12 @@ public class LambdaExecutorService implements Resettable {
} catch (Exception e) {
Throwable cause = e instanceof ExecutionException && e.getCause() != null ? e.getCause() : e;
if (cause instanceof TimeoutException) {
LOG.warnv("Function {0} timed out after {1}s", fn.getFunctionName(), fn.getTimeout());
if (initializing && !invocation.getDispatchedFuture().isDone()) {
LOG.warnv("Function {0} did not finish its init within {1}s of its container starting; raise floci.services.lambda.init-timeout-seconds if its init is slow",
fn.getFunctionName(), initTimeoutSeconds);
} else {
LOG.warnv("Function {0} timed out after {1}s", fn.getFunctionName(), fn.getTimeout());
}
warmPool.destroyHandle(handle);
return new InvokeResult(200, "Unhandled",
buildErrorPayload("Task timed out after " + fn.getTimeout() + " seconds", "Function.TimedOut"),
@@ -397,6 +418,21 @@ public class LambdaExecutorService implements Resettable {
}
}
/**
* How long an invocation waits for its runtime to take it. A runtime that has never polled /next
* is still in its Init phase, which runs from its container's start for the Init budget; once the
* runtime polls, only the function's Timeout and a dispatch grace apply. The Timeout itself
* restarts when the invocation is dispatched (PendingInvocation#prepareForDispatch).
*/
long dispatchWaitMs(int timeoutSeconds, boolean initializing, long containerStartedAtMs, long nowMs) {
long dispatchWaitMs = (timeoutSeconds + RUNTIME_DISPATCH_GRACE_SECONDS) * 1000L;
if (!initializing) {
return dispatchWaitMs;
}
long sinceStartMs = containerStartedAtMs > 0 ? Math.max(0, nowMs - containerStartedAtMs) : 0;
return Math.max(initTimeoutSeconds * 1000L - sinceStartMs, dispatchWaitMs);
}
/**
* Drops the pending asynchronous events of a deleted function: AWS runs no further attempt and
* delivers no record for them. DeleteFunction calls it twice. The call before it drains the warm pool
@@ -55,6 +55,7 @@ public class SqsEventSourcePoller implements Resettable {
private final LambdaTargetResolver targetResolver;
private final EsmStore esmStore;
private final long pollIntervalMs;
private final int initTimeoutSeconds;
private final String baseUrl;
private final ObjectMapper objectMapper;
private final PipesFilterMatcher filterMatcher;
@@ -85,6 +86,7 @@ public class SqsEventSourcePoller implements Resettable {
this.targetResolver = targetResolver;
this.esmStore = esmStore;
this.pollIntervalMs = config.services().lambda().pollIntervalMs();
this.initTimeoutSeconds = Math.max(0, config.services().lambda().initTimeoutSeconds());
this.baseUrl = config.effectiveBaseUrl();
this.objectMapper = objectMapper;
this.filterMatcher = filterMatcher;
@@ -183,11 +185,12 @@ public class SqsEventSourcePoller implements Resettable {
// the window since the first buffered message expires.
int window = esm.getMaximumBatchingWindowInSeconds() == null
? 0 : esm.getMaximumBatchingWindowInSeconds();
// A message can be buffered for the whole window and then processed for the full
// function timeout, so visibility has to cover both plus AWS's 30s margin, not the
// larger of the two. Otherwise a long invoke can outlive the visibility and another
// consumer receives the message, causing a duplicate delivery and a stale handle.
int visibilityTimeout = fn.getTimeout() + Math.max(window, 0) + 30;
// A message can be buffered for the whole window, wait out a cold start's Init
// budget and then be processed for the full function timeout, so visibility has to
// cover all three plus AWS's 30s margin, not the largest of them. Otherwise a long
// invoke can outlive the visibility and another consumer receives the message,
// causing a duplicate delivery and a stale handle.
int visibilityTimeout = fn.getTimeout() + Math.max(window, 0) + initTimeoutSeconds + 30;
PendingBatch pending = pendingBatches.get(esm.getUuid());
int alreadyBuffered = pending != null ? pending.messages.size() : 0;
@@ -439,6 +439,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
// Now start the container with code in place
lifecycleManager.startCreated(containerId, spec);
runtimeApiServer.markContainerStarted();
watchForUnexpectedExit(dockerClient, containerId, runtimeApiServer);
// Extensions can log as soon as they start, which is before the container's own log stream
@@ -229,6 +229,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
LOG.infov("Created pod {0} for function {1}", podName, fn.getFunctionName());
awaitRunning(namespace, podName, fn.getFunctionName());
runtimeApiServer.markContainerStarted();
ContainerHandle handle = new ContainerHandle(podName, fn.getFunctionName(),
runtimeApiServer, ContainerState.WARM, false);
@@ -114,6 +114,8 @@ public class RuntimeApiServer {
private final Object lock = new Object();
private final CompletableFuture<Void> initialization = new CompletableFuture<>();
private boolean runtimeNextReceived;
// When the launcher started this runtime's container, in epoch millis; 0 until then.
private volatile long containerStartedAtMs;
// Invocations queued before a /next poller arrived. Guarded by lock.
private final ArrayDeque<PendingInvocation> pendingQueue = new ArrayDeque<>();
@@ -309,6 +311,26 @@ public class RuntimeApiServer {
}
}
/** Records that the container running this runtime has started, which opens its Init phase. */
public void markContainerStarted() {
containerStartedAtMs = System.currentTimeMillis();
}
/** Epoch millis at which the container started, or 0 when no launcher has recorded it. */
public long getContainerStartedAtMs() {
return containerStartedAtMs;
}
/**
* Whether the runtime has polled {@code /next} at least once, which ends its Init phase.
* Unlike {@link #isInitialized()} this does not wait for extensions.
*/
public boolean hasRuntimePolled() {
synchronized (lock) {
return runtimeNextReceived;
}
}
private void completeInitializationIfReady() {
synchronized (lock) {
CountDownLatch latch = extensionsReady;