Skip to content

Feature request: @app.warmup decorator for AgentCore Runtime build-warmup lifecycle hooks #741

Done

Description

@naviret

Is your feature request related to a problem? Please describe.

AgentCore Runtime lifecycle hooks let an agent prepare itself during CreateAgentRuntime / UpdateAgentRuntime, before the runtime is READY. With a build warmup hook configured (hooksConfiguration.build.warmup.action.httpPost), AgentCore Runtime sends two POST requests to the agent, in order, with the header X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type set to:

  • memory: load into memory what every session needs (imports, models, caches). Each new instance starts with what's loaded here.
  • disk: read the files that sessions read at start, so AgentCore Runtime can make them available faster to new sessions.

Any 2xx response is success. Any other status, a failed connection, or exceeding the shared 120 s limit fails the create/update. The docs also require that /ping keeps answering while the warmup runs.

BedrockAgentCoreApp has no support for this, so every agent re-implements the same pieces:

  • a route;
  • header parsing and validation;
  • running blocking work without blocking /ping;
  • mapping exceptions to status codes;
  • answering the warmup type it has nothing to do for.

Getting any of these wrong fails the build: blocking the event loop stalls /ping, and a missing branch for one type returns an error.

Describe the solution you'd like

A decorator next to @app.entrypoint and @app.ping:

from bedrock_agentcore.runtime import BedrockAgentCoreApp, WarmupType

app = BedrockAgentCoreApp()
MODEL = None

@app.warmup(WarmupType.MEMORY)
def load_model():
    global MODEL
    MODEL = load("/opt/model.bin")          # every new instance starts with this loaded

@app.warmup(WarmupType.DISK)
def read_startup_files():
    for path in STARTUP_FILES:              # files sessions read at start
        with open(path, "rb") as f:
            while f.read(1 << 20):
                pass

@app.entrypoint
def invoke(payload):
    return MODEL.predict(payload)

if __name__ == "__main__":
    app.run()

Runtime configuration (the default port is the agent's serving port, so it can be left out):

client.create_agent_runtime(
    ...,
    platformVersion="V2",
    hooksConfiguration={"build": {"warmup": {"action": {"httpPost": {"path": "/warmup"}}}}},
)

Local test:

python app.py &
curl -X POST localhost:8080/warmup -H 'X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type: memory'
# {"status": "ok", "type": "memory", "result": "completed"}

One handler, both, or none are all valid.

Proposed implementation (runtime/models.py, runtime/app.py)

# models.py
class WarmupType(str, Enum):
    MEMORY = "memory"
    DISK = "disk"

WARMUP_TYPE_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type"
# app.py: BedrockAgentCoreApp
def __init__(self, debug=False, lifespan=None, middleware=None, warmup_path: str = "/warmup"):
    ...
    self._warmup_handlers: Dict[WarmupType, Callable] = {}
    self._warmup_lock = asyncio.Lock()
    routes = [
        Route("/invocations", self._handle_invocation, methods=["POST"]),
        Route("/ping", self._handle_ping, methods=["GET"]),
        Route(warmup_path, self._handle_warmup, methods=["POST"]),
        WebSocketRoute("/ws", self._handle_websocket),
    ]
    ...

def warmup(self, type: WarmupType) -> Callable[[Callable], Callable]:
    """Register a build-warmup handler for one warmup type (memory or disk).

    Register zero, one or both. A type without a handler is answered with 200 (nothing to do).
    Sync handlers run in the thread pool and async handlers on the worker loop, so /ping keeps answering.
    An exception in the handler returns 500, which fails the create/update.
    """
    t = WarmupType(type)                                    # unknown type → ValueError at import time
    if t in self._warmup_handlers:
        raise ValueError(f"a {t.value} warmup handler is already registered")

    def register(func: Callable) -> Callable:
        self._warmup_handlers[t] = func
        return func
    return register

async def _handle_warmup(self, request):
    raw = request.headers.get(WARMUP_TYPE_HEADER, "").strip().lower()
    try:
        t = WarmupType(raw)
    except ValueError:
        return JSONResponse({"error": f"{WARMUP_TYPE_HEADER} must be memory or disk, got {raw!r}"}, status_code=400)
    handler = self._warmup_handlers.get(t)
    if handler is None:
        self.logger.info("Warmup (%s): no handler registered, nothing to do", t.value)
        return JSONResponse({"status": "ok", "type": t.value, "result": "skipped"})
    async with self._warmup_lock:                           # never run two warmups at once in one process
        start = time.time()
        try:
            await self._invoke_handler(handler, None, False, None)
        except Exception as e:
            self.logger.exception("Warmup (%s) failed (%.3fs)", t.value, time.time() - start)
            return JSONResponse({"error": str(e), "type": t.value}, status_code=500)
        self.logger.info("Warmup (%s) completed (%.3fs)", t.value, time.time() - start)
    return JSONResponse({"status": "ok", "type": t.value, "result": "completed"})

Design decisions

Decision Why
The decorator registers; the route always exists Same pattern as @app.entrypoint. Turning on hooksConfiguration for an app with no warmup code still builds.
A missing handler → 200 skipped Both types are always called. A memory-only agent must not fail on the disk call, and nobody should have to write def disk(): pass. The log line still shows a handler that was expected but never registered.
A handler exception → 500 Any non-2xx fails the build by contract. A half-prepared agent is worse than a failed build, and the logged exception explains it.
A bad or missing header → 400 The call is malformed. Skipping it would hide an integration problem.
Reuse _invoke_handler Sync handlers go to the thread pool and async ones to the worker loop, which satisfies "keep /ping responsive" without customer code. /ping reports its normal status during warmup.
An asyncio.Lock The platform makes one call at a time and doesn't retry. The lock is a cheap guarantee that a handler never runs twice concurrently in one process (local testing, a misconfigured caller), so handlers don't need their own locking. It's an asyncio lock because _handle_warmup runs on the event loop: a thread lock there would block /ping.
Programming errors at import time An unknown type or a duplicate registration raises when the module loads: caught locally, not by a create that takes minutes.
Completion logs Warmup (memory) completed (8.214s) mirrors Invocation completed successfully (Ns). It goes to the runtime's build logs next to the platform's [LIFECYCLE] lines.
warmup_path, default /warmup httpPost.path is required and customer-chosen. Matching the documented example keeps the common case zero-config. The port is the app's own, which is also the API's default for httpPost.port.

Proposed tests (Starlette TestClient)

  • Memory-only app: disk → 200 skipped; memory → 200, and the handler ran once.
  • No handlers: both types → 200.
  • Missing or unknown header → 400.
  • A raising handler → 500 with type.
  • A duplicate registration → ValueError.
  • Sync and async handlers both work; a sync handler sleeping 2 s doesn't delay a concurrent GET /ping.
  • Two overlapping warmup calls → the handler runs sequentially.

Describe alternatives you've considered

  • Requiring both handlers: no-op boilerplate in most agents, and a build failure for a missing one.
  • One handler receiving the type (@app.warmup def w(type)): every customer writes the same dispatch. It could be added later as a no-argument form.
  • A raw Starlette/FastAPI route: what the docs example shows today. It works, but every agent re-implements thread offloading, validation and error mapping.

Additional context / open questions

  1. A docs note for memory: reading a file and throwing the data away in the memory call doesn't help sessions. The data has to stay in the process: a variable, or a mapping that a running process holds. Plain file reads belong in the disk call.
  2. Per-instance setup: anything loaded in the memory call is shared by every instance that starts from it. That includes random seeds, temporary credentials and open connections. Some agents will need to run code once per instance, when it starts from the prepared state. That needs a signal from the runtime at that moment. Is there such a signal, or is one planned? The SDK could expose it the same way as the warmup handlers.
  3. Custom invocation path: the API supports protocolConfiguration.path, but BedrockAgentCoreApp hard-codes /invocations. That's separate from this request; noting it for completeness.

Activity

  1. added
    enhancement
    on Nov 13, 2026
  2. siwachabhi commented on Nov 16, 2026

    @siwachabhi
    Contributor

    customer should be able to provide the warmup path, with a default as /warmup, since in api it will be a required param

  3. added 2 commits that reference this issue on Nov 18, 2026
    4feb80f
    639971d
  4. added a commit that references this issue on Nov 28, 2026
    62f8fc6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions