Reminiscence lifecycle insurance policies assist long-running brokers on Amazon Bedrock AgentCore keep efficient by systematically managing what they bear in mind and neglect. Your agent generates recollections from each dialog it conducts. If you happen to don’t actively handle these recollections, your brokers will accumulate outdated context, which might degrade response high quality and create compliance dangers to your deployment.
After months of manufacturing use, issues emerge. We noticed a buyer assist agent reference a billing dispute resolved 4 months earlier, treating it as energetic. One other agent repeated outdated deployment recommendation as a result of its reminiscence nonetheless contained a outdated runbook.
On this publish, we introduce reminiscence lifecycle administration for AI brokers: the observe of systematically scoring, consolidating, and pruning agent recollections over time. We stroll by a deployable structure utilizing AgentCore reminiscence (a functionality of Amazon Bedrock AgentCore), AWS Step Features, and Amazon Bedrock to run a nightly lifecycle workflow. By the top, you should have an AWS Cloud Growth Package (AWS CDK) stack and a framework for managing agent reminiscence as a managed useful resource. The entire code is accessible within the GitHub repository.
This resolution targets brokers that accumulate excessive volumes of interplay knowledge over weeks or months, corresponding to buyer assist brokers, gross sales advisors, and IT helpdesk bots. For lower-volume brokers like private assistants, you may begin with time-to-live (TTL) expiration and Common Information Safety Regulation (GDPR) compliance alone. All thresholds are configurable to match your agent’s wants.
Answer overview
This resolution combines a shared reminiscence taxonomy with three lifecycle insurance policies that run as a nightly workflow. We start with the reminiscence varieties that form these insurance policies.
Reminiscence varieties
Earlier than designing lifecycle insurance policies, we want a shared vocabulary for what brokers bear in mind. We categorize agent reminiscence into three varieties, every with totally different retention necessities.
- Episodic reminiscence: Episodic recollections seize what occurred, it’s the file of previous conversations. These are timestamped, session-bound, and high-volume. Agentcore reminiscence shops this data in two methods, Abstract and Episodic. Each methods retailer recollections as particular person entries tied to particular agent-user periods. Episodes and Abstract present short-term continuity however individually they turn into much less related as time progresses. When designing your lifecycle insurance policies, prioritize these recollections for expiration first.
- Semantic reminiscence: Semantic recollections are distilled details and preferences extracted from interactions however decoupled from any single dialog. “The consumer prefers the US East (N. Virginia) AWS Area (us-east-1) for deployments.” These are sturdy, excessive worth, and compact. In your lifecycle insurance policies, retain semantic recollections longer than episodic recollections. These are prime candidates for consolidation, the place you merge a number of episodic observations right into a single, authoritative truth.
- Procedural reminiscence: Procedural recollections encode realized workflows and tool-use patterns. “When the consumer asks about prices, question the AWS Value Explorer API first, then summarize.” These characterize the agent’s operational experience. Procedural recollections are decrease quantity however essentially the most invaluable kind for sure use instances. They’ve the longest retention and the very best bar for pruning. AgentCore reminiscence shops procedural data as reflections tied to episodic reminiscence. Learn extra about it in Episodic reminiscence deep dive weblog. It is best to examine these for validity as your procedures evolve.
Lifecycle insurance policies
With our taxonomy in place, we will design three complementary lifecycle insurance policies. Every targets a unique failure mode of unbounded reminiscence.
Coverage 1: TTL-based expiration
The primary coverage routinely deletes recollections older than a configured TTL. We default to 90 days for episodic recollections. TTL doesn’t take into account whether or not a reminiscence continues to be helpful, but it surely gives a tough ceiling on accumulation and is important for compliance.
In manufacturing, differentiate TTL by reminiscence kind. Configure your abstract recollections to run out after 30–60 days, semantic recollections after 6–12 months, and take into account setting no TTL for procedural recollections. This publish delivers a single configurable memoryTtlDays parameter as a place to begin. TTL expiration runs first, earlier than scoring or consolidation, which helps keep away from losing compute on recollections that ought to already be gone.
AgentCore reminiscence doesn’t present a built-in auto-delete TTL. Nevertheless, it exposes system-generated timestamp fields that assist BEFORE and AFTER filter operators on ListMemoryRecords. Our pruner makes use of x-amz-agentcore-memory-createdAt with a BEFORE filter to retrieve solely information older than the configured TTL, then deletes them.
Coverage 2: Relevance decay scoring
Not all recollections age on the similar charge. A reminiscence accessed yesterday is extra related than one untouched for weeks. We rating every reminiscence utilizing a three-term weighted system that mixes creation recency, last-access recency, and entry frequency:
Moderately than exposing a uncooked decay fixed, we offer one intuitive parameter: pruneDays, the approximate variety of days after which an unaccessed reminiscence’s rating drops beneath the relevance threshold:
With the defaults (pruneDays = 45, threshold = 0.3), this provides decay_rate ≈ 0.02676. The system produces a rating between 0.0–1.0. When recollections rating beneath your configured threshold, the system flags them for consolidation or pruning primarily based in your coverage settings.
The system balances three intuitions: current recollections matter, lately used recollections matter much more, and steadily retrieved recollections carry further sign. The exponential decay means scores drop sharply within the first few weeks, then degree off. A reminiscence that’s previous however accessed lately and steadily can nonetheless rating properly.
The three weights are configurable, letting operators emphasize totally different indicators relying on their agent’s workload:
W_RECENCY(default 0.4): Weight for creation recency. Increased values favor newer recollections.W_ACCESS(default 0.35): Weight for last-access recency. Increased values favor lately retrieved recollections.W_FREQUENCY(default 0.25): Weight for entry frequency. Increased values favor recollections which might be retrieved typically.MAX_ACCESS_BASELINE(default 50): The entry rely at which the frequency time period saturates at 1.0. Set this to the approximate variety of accesses a “closely used” reminiscence accumulates in your lookback window.
When the three weights sum to 1.0, the rating will fall in [0.0, 1.0]. Operators can regulate weights to match their agent’s wants. For instance, enhance W_FREQUENCY for brokers the place steadily accessed recollections are most respected (for instance, a assist bot that repeatedly references the identical troubleshooting runbook), or enhance W_RECENCY for brokers the place freshness issues most (for instance, a real-time buying and selling assistant).
The best pruneDays worth relies on your agent’s use case. The next desk gives beneficial beginning factors for frequent agent archetypes:
| Agent kind | pruneDays | Rationale |
| Actual-time assist bot | 7 | Tickets resolve in hours/days. Previous context is just not wanted |
| Gross sales / onboarding agent | 21 | Offers shut in weeks. Stale leads pollute context |
| Common assistant | 45 | Balanced retention for blended workloads |
| IT helpdesk / ops agent | 90 | Incident patterns repeat seasonally |
| Authorized / compliance advisor | 180 | Precedents keep related for months |
The next scoring operate comes from our Reminiscence Scorer AWS Lambda operate (code/lambdas/memory_scorer/handler.py):
AWS CloudTrail-based entry monitoring
The AgentCore reminiscence API doesn’t embrace a lastAccessedAt subject in its MemoryRecordSummary. To get actual entry knowledge, we use AWS CloudTrail. The CDK stack configures a path with superior occasion selectors that seize GetMemoryRecord knowledge occasions. Your CloudTrail configuration logs each reminiscence retrieval with its memoryRecordId and timestamp, then delivers the logs to your Amazon Easy Storage Service (Amazon S3) bucket. At the beginning of every scoring invocation, the Reminiscence Scorer lists CloudTrail log recordsdata from the previous 25 hours, decompresses them, and aggregates GetMemoryRecord occasions right into a per-record lookup of last-access timestamps and entry counts. To take care of cumulative entry historical past throughout invocations, the scorer persists an entry ledger in Amazon S3. Every run merges contemporary CloudTrail counts with historic counts, giving the frequency time period a real lifetime sign slightly than a slim each day snapshot.
Coverage 3: LLM-based consolidation
Earlier than pruning low-scoring recollections, we give them one final likelihood. Consolidation makes use of Amazon Bedrock to merge associated recollections right into a single, compact semantic entry. 5 episodic recollections about deployment preferences turn into one authoritative truth. On this step, a big language mannequin (LLM) summarizes its personal recollections. The consolidation immediate instructs the mannequin to protect important details, take away redundancy, and output a confidence rating:
The system shops the consolidated reminiscence again in AgentCore reminiscence, then deletes the originals. If Amazon Bedrock fails, the system retains the originals unchanged. The system logs failed deletions to your handbook overview. Consolidation is lossy by nature. An LLM summarizing 5 recollections into one can drop some nuance. The arrogance rating returned by the mannequin helps flag low-quality consolidations for human overview. For prime-stakes domains, take into account archiving originals to chilly storage as a substitute of deleting them.
For manufacturing deployments, configure Amazon Bedrock Guardrails to filter dangerous content material and use grounding checks to confirm consolidated recollections stay devoted to the supply materials. These controls are manufacturing necessities, not non-compulsory additions.
Structure diagram
The next diagram exhibits the nightly lifecycle workflow structure. Amazon EventBridge triggers an AWS Step Features state machine that orchestrates 5 Lambda capabilities in sequence.
Determine 1: Nightly reminiscence lifecycle workflow orchestrated by Amazon EventBridge and AWS Step Features
Textual content description for accessibility: An Amazon EventBridge rule triggers a Step Features state machine nightly. The state machine invokes Lambda capabilities in sequence: Reminiscence Pruner (TTL expiration), Reminiscence Scorer (relevance scoring utilizing CloudTrail entry knowledge), Reminiscence Consolidator (LLM-based merging by Amazon Bedrock), Metrics Emitter (Amazon CloudWatch metrics), and Run Output Author (S3 persistence). Failures path to an Amazon Easy Notification Service (Amazon SNS) subject for alerts.
The workflow proceeds as follows:
- TTL Expiration: The Reminiscence Pruner queries AgentCore reminiscence for information older than the configured TTL (default: 90 days) and deletes them.
- Rating Reminiscences: The Reminiscence Scorer builds a per-record entry lookup from CloudTrail logs, merges it with a persistent S3 ledger, computes relevance scores, and returns recollections beneath the brink.
- Consolidate: The workflow batches low-scoring recollections (default measurement: 10) and sends them to the Reminiscence Consolidator, which invokes Amazon Bedrock to merge them into compact semantic entries and deletes the originals.
- Emit Metrics: The Metrics Emitter publishes workflow metrics (recollections processed, consolidated, pruned) to CloudWatch.
- Write Run Output: The Run Output Author persists workflow outcomes to S3 for auditability. If any step fails, a Catch block routes to a failure handler that publishes error particulars to an Amazon SNS subject.
Conditions
Earlier than deploying the answer, affirm you’ve the next:
- An AWS account with permissions to create Lambda capabilities, Step Features state machines, Amazon EventBridge guidelines, SNS subjects, CloudWatch dashboards, CloudTrail trails, and S3 buckets.
- AWS CDK v2 put in (
npm set up -g aws-cdk). - Node.js 18+ and npm.
- Python 3.12 with pip.
- Amazon Bedrock mannequin entry enabled for Claude Sonnet 4.5 (
anthropic.claude-sonnet-4-5-20250929-v1:0) in your goal Area. See Supported fashions by AWS Area in Amazon Bedrock to confirm availability. - Amazon Bedrock AgentCore with no less than one agent configured with reminiscence enabled.
- AWS Command Line Interface (AWS CLI) configured with applicable credentials.
Clone the repository and set up dependencies:
Answer walkthrough
We orchestrate all the lifecycle as a nightly AWS Step Features workflow triggered by Amazon EventBridge. The workflow runs 5 levels in sequence: TTL expiration, scoring, consolidation, metrics emission, and run output writing.
CDK stack walkthrough
A single CDK stack (code/lib/memory-lifecycle-stack.ts) defines all the infrastructure. Listed below are the important thing sections.
Lambda operate definitions: Every handler makes use of Python 3.12 with least-privilege IAM permissions. The stack deploys shared code as a Lambda Layer and passes configurable parameters as atmosphere variables:
AWS Identification and Entry Administration (IAM) least-privilege: The Reminiscence Scorer can solely record recollections. The Consolidator can learn, create, delete recollections and invoke Amazon Bedrock. The Pruner can record and delete:
Step Features workflow: The state machine chains TTL expiration, scoring, a Alternative state for low-score recollections, batch consolidation (Map state), metrics emission, and run output writing:
Nightly set off: An Amazon EventBridge rule fires the workflow at 2 AM UTC daily:
All configurable parameters (memoryTtlDays, relevanceThreshold, consolidationBatchSize, pruneDays, bedrockModelId, and the scoring weights) are learn from CDK context, so you’ll be able to tune them at deploy time with out altering code:
Value issues
The first value driver is Amazon Bedrock invocations throughout consolidation. For an agent with 1,000 recollections the place 20 p.c rating beneath the brink, count on roughly 20 Bedrock invocations per nightly run (about $0.01–$0.02). At 100,000 recollections, this might attain $50–$100 monthly. Begin with a better relevance threshold to restrict consolidation quantity, and overview Amazon Bedrock pricing to your particular workload.
Testing reminiscence high quality
Pruning and consolidation are solely helpful if the agent nonetheless solutions appropriately afterward. We measure whether or not lifecycle operations degrade response high quality utilizing a regression check suite.
Reminiscence regression check suite
We outline check instances as question-and-criteria pairs (code/check/test_regression_suite.py). Every check case specifies a query, the factors the agent’s response ought to fulfill, and a minimal high quality rating:
The regression suite follows a before-and-after sample:
- Baseline: Question the agent with every check query earlier than the lifecycle run. Document the standard rating utilizing AgentCore Evaluations, a functionality of Amazon Bedrock AgentCore.
- Run lifecycle: Execute the nightly workflow (scoring, consolidation, pruning).
- Publish-lifecycle: Question the agent once more with the identical questions. Document new high quality scores.
- Consider: A check case passes if the post-lifecycle rating meets or exceeds the configured minimal. We additionally compute the standard delta (
post_lifecycle_score - baseline_score) for reporting.
AgentCore Evaluations integration
The regression suite integrates with Amazon Bedrock AgentCore Evaluations to compute high quality scores programmatically. AgentCore Evaluations works as an LLM-as-judge system: you present the agent’s response and human-defined standards, and the service returns a normalized high quality rating between 0.0 and 1.0. This makes the suite absolutely automated and appropriate for steady integration and steady supply (CI/CD) pipelines.
Operating the suite produces a per-test-case report that pairs the baseline and post-lifecycle scores so you’ll be able to see the standard delta at a look:
On this pattern run, each check instances keep above their configured minimums. A check case fails solely when the post-lifecycle rating drops beneath its min_quality_score, signaling that pruning or consolidation went too far.
Privateness and compliance
Reminiscence lifecycle administration is just not solely about efficiency. It’s a compliance requirement. When your agent shops private knowledge in reminiscence, you inherit obligations below laws like GDPR.
GDPR right-to-be-forgotten
A devoted GDPR Deletion Handler (code/lambdas/gdpr_deletion/handler.py) deletes all recollections for a selected consumer. It lists each reminiscence for that consumer in AgentCore reminiscence and deletes them individually:
The handler returns a affirmation with the rely of deleted recollections and any failed IDs. On partial failure, the response consists of the failed reminiscence identifiers so operators can examine and retry.
Audit logging with CloudTrail
Each reminiscence mutation (scoring, consolidation, pruning, GDPR deletion) produces structured JSON logs in Amazon CloudWatch Logs with motion kind, reminiscence ID, and ISO 8601 timestamp.
The CDK stack additionally configures AWS CloudTrail to log AgentCore reminiscence API calls, offering an immutable audit path for compliance demonstrations:
The stack creates an Amazon CloudWatch dashboard displaying recollections processed, consolidated, pruned, and workflow execution standing for real-time operational visibility.
Clear up
To take away all sources created by this resolution, run:
This removes all sources created by the stack. You may must delete CloudWatch log teams created by Lambda executions individually.
Conclusion
We confirmed how one can construct reminiscence lifecycle insurance policies for Amazon Bedrock AgentCore brokers utilizing AWS Step Features and Amazon Bedrock. The answer applies three complementary insurance policies: TTL expiration for exhausting cut-off dates, relevance decay scoring for clever prioritization, and LLM-based consolidation for preserving data. With the pruneDays parameter, you’ll be able to tune decay aggressiveness. We additionally lined testing to verify pruning doesn’t degrade high quality, and GDPR compliance on the reminiscence layer.
The complete code is accessible within the GitHub repository. Deploy it with npx cdk deploy -c pruneDays=45 and begin operating nightly reminiscence lifecycle administration to your brokers.
To study extra, see the Amazon Bedrock AgentCore documentation, the Amazon Bedrock AgentCore element web page, the AWS Step Features Developer Information, and the Amazon Bedrock Person Information.
Concerning the authors

