Brokers right this moment overview code, course of claims, and run unattended for hours. Many additionally sit behind interactive experiences the place an individual waits for the primary response. Amazon Bedrock AgentCore runtime provides these brokers a totally managed, serverless setting: every session runs in its personal remoted microVM, the platform scales to zero when there’s no work, and also you solely pay for the sources your periods devour.
AgentCore runtime with platformVersion set to “V2” adjustments how periods begin. As a substitute of initializing your container for each session, it prepares your setting as soon as, snapshots it, and restores that snapshot for every new session. Session begin occasions are sooner and extra constant. V2 additionally reclaims reminiscence your periods don’t use, so your invoice tracks what your agent makes use of.
For many brokers, switching to V2 is all it takes. Some brokers want restructuring to get the complete profit, and for chat and voice experiences even 2 seconds is just too sluggish. This submit explains how V2 begins a session, the best way to measure session begin time, and the best way to hold work off the primary request, together with construct hooks, which AgentCore runtime now helps. We cowl 4 patterns, from adjustments to your agent’s code to beginning periods earlier than customers want them.
Which sample do you want?
| Your scenario | What to do | Part |
| A brand new session in about 2 seconds is ok | Change to V2 and do all initialization earlier than app.run() |
Hold work off the primary request |
| Your agent wants giant information, a CLI, or a browser early, and might’t maintain them in its course of | Add a construct hook to load and prime them whereas the snapshot is constructed | Working with hooks |
| You want sub-second, and customers interact earlier than they ship their first request (opening the app or a chat window) | Begin the session within the background when the consumer engages | Pre-warm on consumer engagement |
How V2 begins a session
AgentCore runtime runs every session in a brand new microVM. On V1, AgentCore pulls your container picture from Amazon Elastic Container Registry (Amazon ECR), begins the container, and runs your initialization code earlier than it may possibly course of the primary request. The picture pull dominates, so chilly begin grows with picture dimension.
V2 does that work as soon as. If you create or replace a runtime, AgentCore runtime begins your container in a recent microVM and waits for the primary wholesome ping (GET /ping), which should arrive inside 120 seconds. It then clears the working system’s file cache, to maintain the snapshot small, freezes the microVM, and shops its reminiscence and disk as a snapshot.
It is a change from V1: Each create or replace now takes a couple of minutes whereas the snapshot is constructed.
On this submit, init means all the things your agent does earlier than /ping reviews wholesome. With the AgentCore Python SDK, that’s all the things earlier than app.run(). Should you run your personal HTTP server, in Node.js or one other language, report wholesome solely after your initialization finishes.
When a brand new session arrives, AgentCore restores the snapshot into a brand new microVM. Your course of resumes precisely the place it was frozen, with its imports, objects, and purchasers in place. Information out of your picture are loaded lazily: every block is fetched the primary time a session reads it.
Three information observe from these flows, and the remainder of this submit builds on them:
- Reminiscence comes again entire. Something your course of held at snapshot time, and something in a RAM-backed file system corresponding to
/dev/shm, is on the market at reminiscence velocity from the primary entry. - File reads don’t carry over. The file cache is cleared earlier than the freeze, so studying a file throughout init doesn’t make it quick in a restored session.
- Picture information are fetched on first learn. The primary learn of a block comes from snapshot storage and is then cached nearer to the host.
The next desk exhibits what meaning for the work a typical agent does, relying on the place it does it:
| Work | Carried out throughout init | Carried out within the handler |
| Import libraries | In reminiscence when the session begins | Learn from the picture in each new session |
Create purchasers (for instance, boto3) |
Restored with endpoint and credential decision performed. Sockets reconnect on first use | Constructed from scratch in each new session |
| Open community connections | Stale after the restore. Shut them earlier than the snapshot | Opened recent |
| Load static knowledge from the picture and hold it in an object | In reminiscence when the session begins | Learn from the picture in each new session |
| Learn a file from the picture with out holding the info | No impact, as a result of the file cache is cleared | Learn from the picture in each new session |
If you already know AWS Lambda SnapStart, it will really feel acquainted. Marc Brooker’s submit on how SnapStart masses snapshots and the SnapStart priming methods submit are helpful background.
Every thing within the desk assumes your agent can hold what it wants in its personal course of. That isn’t all the time attainable. A CLI that runs as a separate course of and exits, or a browser binary, is learn throughout init after which gone, so a restored session fetches it from the picture once more. For these circumstances, you may add a construct hook, lined in “Working with hooks.” Determine 3 exhibits the place it runs.
Measure earlier than you optimize
Latency in an agentic software isn’t one quantity. A request spends time in AgentCore runtime getting a session able to run your code, then in your code: mannequin calls, software calls, sub-agents, and streaming the response again. You repair these in numerous methods, so begin by discovering out which one dominates.
AgentCore runtime publishes each as Amazon CloudWatch metrics within the AWS/Bedrock-AgentCore namespace. Latency is the time to first byte. OverheadLatency is the half that belongs to the platform, corresponding to beginning the microVM and restoring the snapshot on a brand new session.
| What you need | Tips on how to get it |
| TTFB (Time to first byte) | Latency |
| Runtime time | OverheadLatency |
| Your code’s time | Latency − OverheadLatency |
| Init time | Measured in your code at startup (see the next instance). It isn’t a part of any request on V2 |
Init doesn’t seem in these metrics as a result of on V2 it runs as soon as, whereas the snapshot is constructed, and never in every session. It provides to how lengthy a create or replace takes to achieve READY, to not request latency. To see how lengthy it takes, log it as soon as earlier than app.run(). The road seems in your runtime’s construct logs:
Tips on how to learn the break up:
- Excessive
OverheadLatencyon new periods: the time is in session begin. Use the patterns later on this submit to begin periods earlier than customers want them. - Your code’s time is way increased on the primary request than on the second in the identical session: work that belongs in init is working in your handler. Add customized spans in AgentCore Observability (a functionality of Amazon Bedrock AgentCore) round software setup, file masses, and late imports to search out it, then transfer it into init.
Report percentiles corresponding to P90 and P99, or trimmed means corresponding to TM90, which averages the quickest 90% of requests and drops the slowest tail. A plain common hides the sluggish requests. OverheadLatency covers requests to working periods in addition to new ones, so its distribution depends upon what number of of your requests begin a brand new session. Examine runs with an analogous combine.
Take a look at on the charge of recent periods you anticipate in manufacturing, not with a handful of periods after a deploy.
To incorporate community time out of your shopper, measure on the shopper as properly. Time the invoke name, have your handler return how lengthy it ran, and subtract. Each timestamps come from the identical machine, so clock variations between the shopper and the microVM don’t matter. Should you stream, very small occasions will be held again till a number of hundred bytes of output construct up, so time to first occasion can learn increased than session begin.
Hold work off the primary request
The standard chilly begin recommendation is to import lazily and hold initialization small. On V2, do the alternative: init runs as soon as, when the snapshot is constructed, and work deferred to the handler is paid by each new session. This is applicable to static work: imports, purchasers, and knowledge out of your picture. Dynamic knowledge can’t be snapshotted. The following part covers it.
The brokers that discover most are those that learn giant information from their picture at request time: weights for a small native mannequin, embeddings, datasets, giant libraries, a browser binary for automation, or a CLI toolchain {that a} coding agent runs as subprocesses. Studying many small information, as compiling a TypeScript mission does, has the identical impact. An agent that imports a number of libraries and calls a hosted mannequin principally must get its imports and purchasers proper.
Tips on how to restructure your agent
Create objects throughout init, not solely imports. Creating an object masses the modules it depends upon and retains them in energetic reminiscence. Initialize native instruments that use exterior libraries throughout init too, not when the agent first calls them.
Create your purchasers throughout init. Endpoint decision, credential decision, and the shopper’s modules all come again with the snapshot. Sockets don’t, however boto3 purchasers reconnect cleanly on the primary name. Another community purchasers first strive the stale socket, which provides a whole lot of milliseconds, so shut their connections earlier than the snapshot.
Hold static knowledge in reminiscence, corresponding to prompts, ability entrance matter, configuration, and small indexes. Maintain the info in an object, not solely a learn of it:
Hold instruments working as an alternative of beginning them per request. A subprocess launched within the handler reads its binary and libraries from the picture in each new session. A protracted-running helper began throughout init, corresponding to a language server or a employee course of with its imports performed, comes again as a part of course of reminiscence. Discuss to it over a pipe or socket.
Copy information you may’t maintain in reminiscence to a RAM-backed disk. Toolchains like tsc run as separate applications that learn their very own information. Copy them to /dev/shm or a ramfs mount throughout init so their reads come from reminiscence.
Ship compiled bytecode. uv pip set up doesn’t compile by default, so late imports additionally compile from supply. Set UV_COMPILE_BYTECODE=1 or use pip set up --compile.
The instance under builds the agent, its mannequin, and its purchasers throughout init, so each session inherits them:
The trade-off: time to first byte on a brand new session is the time to begin the microVM and restore the snapshot, plus the time your handler takes. Shifting work into init shortens the handler, however something you maintain in reminiscence makes the snapshot bigger. You additionally pay for that held reminiscence in each session. Measure end-to-end session begin earlier than and after the change, so you already know you’ve decreased latency and never solely moved it from the handler to the restore.
Reference card
| Information | Method |
| Giant information the primary request wants, corresponding to a mannequin, a CLI, or a browser | Maintain them in reminiscence throughout init, or prime them with a construct hook |
| Giant reference knowledge learn selectively | Mount Amazon S3 Information or Amazon Elastic File System (Amazon EFS) throughout init, via an entry level (requires digital non-public cloud (VPC) mode) |
| Information the agent not often reads | Depart them on the picture, or transfer them to Amazon Easy Storage Service (Amazon S3), S3 Information, or Amazon EFS |
| Information the session creates | No change wanted |
Working with hooks
A construct hook builds on init and doesn’t substitute it. Do what you may in init and use the hook for what init can’t cowl. You expose an HTTP endpoint in your container, and AgentCore runtime sends it a POST request twice whereas it builds your runtime:
- Earlier than the snapshot. On the construct microVM, after your agent reviews wholesome and earlier than the freeze. Something your agent masses right here and retains in reminiscence is a part of the snapshot, so each session begins with it.
- After a take a look at restore. On a separate microVM that restores the snapshot to test it. Nothing from this name is snapshotted. Use it to learn the information your periods will want, which shapes what restored periods fetch first.
The X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Sort header tells your agent which name it’s dealing with: reminiscence for the primary, disk for the second. The 2 calls share 120 seconds, so the disk name will get no matter time the reminiscence name leaves. Return a 2xx response solely after the work is finished. Some other response, a failed connection, or working out of time fails the create or replace, and AgentCore runtime doesn’t retry. The build-logs- streams in your runtime’s log group present which name failed and why.
Hooks can be found on V2 runtimes. Configure them with hooksConfiguration if you create or replace the runtime:
The port is non-compulsory and defaults to your agent’s serving port. Should you set it, use a port from 8000 to 12000 that isn’t reserved by the platform. The trail can’t match a route AgentCore runtime already makes use of on that port, corresponding to POST /invocations or GET /ping. UpdateAgentRuntime replaces the entire hook configuration, so embrace hooksConfiguration in each replace the place you need to hold the hook.
Within the agent, deal with each name sorts on the identical endpoint:
For the complete configuration reference, see Configure lifecycle hooks for AgentCore runtime. For an entire code instance, see the sample code.
Snapshot pitfalls: What should keep within the handler
Every thing created throughout init is frozen into the snapshot till your subsequent deploy, and each session begins with the identical copy. For many objects that’s the purpose. For the values under, it’s a bug, and for random values, a safety difficulty.
Load dynamic knowledge within the handler, as soon as per session. Software catalogs from AgentCore Gateway (a functionality of Amazon Bedrock AgentCore), characteristic flags, and tariffs change after you deploy. Load them within the handler and cache them at module degree, so every session fetches them as soon as. Periods can last as long as 8 hours, so give the cache an expiry:
Name get_tools() from the handler and cross the consequence to the agent you created throughout init.
Create per-session values within the handler.
| Worth | The place to create it | Why |
| Random values, nonces, secrets and techniques, keys | Within the handler, with secrets and techniques, os.urandom(), or uuid.uuid4() |
Library random state (Python’s random, NumPy) created throughout init is equivalent in each session. Values from the working system are distinctive |
| Present and elapsed time | Within the handler, with time.time() |
An init timestamp is mounted at snapshot time, and time.monotonic() doesn’t depend the time the snapshot spent saved |
| Timers, charge limiters, TTL caches | Use wall-clock time, or reset them on the primary request | Something measuring elapsed time with a monotonic clock sees nearly no hole throughout the restore |
| Credentials and tokens you fetch your self | Refresh them once they expire | Values loaded throughout init can expire earlier than a session begins |
Know the boundaries. A session ends when its idle timeout expires (idleRuntimeSessionTimeout: quarter-hour by default, from 60 seconds as much as 8 hours), when it reaches its most lifetime (maxLifetime: 8 hours by default and at most), or if you cease it.
Sub-second: Begin the session earlier than the consumer wants it
Suppose your new session takes about 2 seconds to begin, together with all of the timing breakdown lined within the previous sections. A session that’s already working solutions in about 200 ms. For a chat or voice expertise, the way in which to sub-second is to ensure the session has began earlier than the consumer’s first request arrives. There are two methods to do this.
Pre-warm on consumer engagement
Most interactive purposes get a sign earlier than the primary immediate: the consumer opens the app, a chat window, or a help web page. Use it. Generate a session ID, ship the agent a warm-up request within the background, and hold the session ID with the dialog. By the point the consumer has typed their first message, the session is working.
This sample wants no further infrastructure and absolutely hides session begin each time customers take greater than about 2 seconds to ship their first message. It prices a session for every consumer who engages however by no means sends a immediate. A brief idle timeout retains that small.
Conclusion
On V2, AgentCore runtime strikes many of the work of beginning a session to deployment time. Your container begins as soon as, and each new session restores the consequence: reminiscence comes again entire, and information are fetched on first learn.
To maintain session startup time close to 2 seconds, do your static work throughout init, maintain the info the primary request wants in reminiscence, and hold dynamic and per-session values within the handler. For information your course of can’t maintain, add a construct hook. To get underneath a second, begin the session earlier than the consumer wants it: on consumer engagement if you get a sign.
To get began, set platformVersion to V2 if you create or replace a runtime, then overview Optimize your agent for AgentCore runtime V2. For questions on your workload, attain out to your AWS account group.
Concerning the creator



