Machine Learning pathway increased my salary by 40%
Agent Memory & Context Engineering
Decide what an agent remembers, forgets and re-reads: working context, episodic and semantic memory, compaction and the cost of carrying too much.
Executive Overview
Context engineering is the discipline of deciding what enters a model’s window at each step. An agent has several kinds of memory: working context for the current task, episodic memory of what happened earlier in a session or across sessions, semantic memory of durable facts, and procedural memory encoded in tools and prompts. Each has different retention, cost and privacy characteristics. Production systems budget context explicitly, summarise or compact conversation history rather than appending indefinitely, retrieve past state on demand instead of carrying it, and store durable facts in governed stores with expiry. The common failures are context overflow disguised as degradation, stale facts recalled as current, and personal data accumulated in memory stores with no retention policy.
Why It Matters in 2026
Long-running agents fail in ways short demos never reveal: the decisive instruction falls out of the window, an outdated preference is recalled, or cost per turn grows until the workflow is uneconomic. Context is also the primary cost driver and the primary privacy surface, since it holds whatever the agent has been told. Treating memory as an engineered subsystem rather than an accumulating array is what makes agents viable over hours, sessions and thousands of users.
Enterprise Relevance: Agent quality degrades predictably as context grows. Memory design determines whether long-running assistants stay coherent, affordable and compliant with data retention rules.
Learning Outcomes
- Budget context across instruction, state, evidence and history
- Design compaction summaries that preserve decisions and constraints
- Separate episodic records from durable facts with different retention
- Retrieve memory on demand instead of carrying it forward
- Govern memory with expiry, access control and deletion
Context Budgeting
Allocate tokens across system instructions, task state, retrieved evidence and history, and enforce the allocation. Without a budget, one verbose tool result crowds out the instructions that keep behaviour correct.
Compaction and Summarisation
History is summarised at defined thresholds with the summary replacing raw turns. Summaries must preserve decisions, commitments and constraints, because those are what later turns depend on.
Episodic versus Semantic Memory
Episodes are what happened; semantics are what is true. Mixing them produces agents that quote outdated conversations as facts. Keep them in separate stores with different retention and confidence.
Retrieval over Retention
Store state durably and fetch it when relevant, rather than carrying everything forward. Retrieval keeps context small and lets memory scale with history rather than with window size.
Memory Governance
Memory stores personal data. They need purpose limitation, expiry, access control and a way to delete on request, because an agent that remembers is a system of record for whatever it was told.
Architecture & Design
A memory architecture separates volatile working context from durable stores. The orchestrator assembles each prompt from a budgeted template, writes episodic records to a session store, extracts durable facts into a governed semantic store, and retrieves relevant memory through the same retrieval layer used for documents.
Architecture Layers
Reference Architectures
Technology Stack
| Layer | Options | What to decide |
|---|---|---|
| Session state | Redis, Postgres, framework checkpointers | Durability versus latency for resumable runs |
| Semantic store | pgvector, dedicated vector store, knowledge graph | Whether facts need relationships |
| Compaction | Model summarisation, extractive rules | What must never be lost in a summary |
| Observability | Tracing with context size per step | How context growth is detected early |
| Governance | Retention jobs, deletion API, field-level access | How erasure requests are satisfied |
Engineering Workflow
Degradation is not obvious
When context overflows, agents rarely error: they become less reliable. Instructions are followed loosely, earlier commitments are forgotten and the model repeats questions. Because the failure is gradual, it looks like model quality rather than a design defect. Instrumenting context size per turn and alerting on growth turns a mystery into a metric.
What a summary must preserve
A useful compaction summary keeps decisions taken, constraints stated by the user, open questions and identifiers needed for later actions. It drops pleasantries and intermediate reasoning. Summarising without those rules produces a shorter conversation that has lost exactly the information later turns depend on.
Operating model for Agent Memory & Context Engineering
Making agent memory & context engineering work over time is an ownership question before it is a tooling question. Someone must hold the quality bar, someone must own the artefacts and someone must own the operational signals. In practice that means a named owner per workflow, a repository location that is the single source of truth, and a review path where changes arrive with evidence attached rather than assertion. The capabilities that matter most in this discipline — context budgeting, conversation compaction, episodic memory design — are learned by doing them on real traffic, so the operating model should create a steady cadence of small changes rather than occasional large ones. Teams that centralise everything in a specialist group create a bottleneck; teams that distribute without shared standards create drift. The workable middle is a platform that provides the shared harness and gates, with product teams owning behaviour and outcomes.
Measurement plan for Agent Memory & Context Engineering
A measurement plan turns agent memory & context engineering from a matter of opinion into a managed process. Start with the outcomes the business already cares about — cost per completed task, handling time, error rates — and attach the engineering signals that lead them: context tokens per turn, compaction frequency, constraint retention rate. Establish a baseline before changing anything, because without it improvement cannot be distinguished from noise. Segment by tenant, document type or intent where behaviour genuinely differs, since averages hide the failures that matter. Set thresholds that block rather than warn, review them quarterly as the system and traffic change, and record the reason whenever a threshold is adjusted. The plan is finished when a new engineer can read it, run the harness and reach the same conclusion the team would.
Working with providers and platforms on Agent Memory & Context Engineering
No team owns this discipline alone: model providers, infrastructure platforms and internal review functions all shape what is possible. The practical work is to define the contract with each. From providers you need change notification, evaluation access and documented behaviour at the versions you actually run, so that an upgrade is a planned event rather than a surprise. From the platform you need the shared capabilities this topic depends on — logging, flags, secret management, queueing — so that product teams do not rebuild them inconsistently. From risk and audit you need agreement on the evidence that will be requested, captured at the point where it is generated. Negotiate these once and write them down. Teams that skip this step spend their time in repeated explanations of behaviour they cannot evidence, and they absorb provider changes as incidents rather than as planned migrations.
Bringing the team with you
Practice changes fail quietly when they are imposed as process. The teams that sustain agent memory & context engineering explain why the gate exists, show the incident it would have prevented, and make the fast path the compliant path. That means templates that already include the artefact, a harness that runs in one command, and a dashboard that answers the question people ask first: is it getting worse? When the tooling makes the right thing easy, adoption follows; when it adds a step with no visible benefit, it is bypassed at the first deadline. Budget time for the first two workflows explicitly, because that is where the habit forms, and treat a caught regression as a success rather than a defect. A team that has experienced one early catch rarely needs persuading again.
Failure modes to design out
Most incidents in this area trace to a small set of predictable design gaps: silent degradation from context overflow; stale facts applied as current; personal data accumulating in memory. Each has a structural remedy rather than a procedural one. Where the risk is silent drift, the remedy is a gate that fails loudly. Where the risk is uncontrolled blast radius, the remedy is narrower scope and a rollback path that has been tested. Where the risk is unowned quality, the remedy is a named owner with time allocated. Designing these out at the start costs a fraction of discovering them in production, and it converts the team's attention from firefighting to improvement. The test of a design is whether a plausible mistake by a competent engineer produces a caught error rather than a customer-visible incident.
Memory Tiers
| Tier | Contents | Retention | Risk |
|---|---|---|---|
| Working context | Current instructions, state, evidence | One turn | Crowding out instructions |
| Session history | Raw turns | Session or short window | Personal data accumulation |
| Episodic memory | Summarised past episodes | Weeks to months | Recalling irrelevant precedent |
| Semantic memory | Durable facts and preferences | Until expiry or erasure | Stale facts treated as current |
Maturity Levels — Agent Memory & Context Engineering
| Level | Characteristics | Evidence you would see |
|---|---|---|
| Ad hoc | Practice depends on individual judgement; changes are unreviewed | No baseline metrics, incidents explained by anecdote |
| Defined | Artefacts are versioned and context budgeting is applied consistently | Repository contains versioned artefacts and a documented process |
| Measured | Context tokens per turn and related signals are tracked per workflow | Dashboards and baselines exist, regressions are detected before users |
| Managed | Thresholds gate releases and ownership is explicit | Changes blocked on evidence, incidents reviewed with recorded actions |
Enterprise Use Cases
Case Study: Cost runaway in a long-running assistant
Case Study: Stale preference recalled as current
Implementation Steps
Practical Project
Operationalise Agent Memory & Context Engineering
Take an existing workflow that relies on agent memory & context engineering and make its behaviour measurable, gated and reversible, without changing the product surface users see.
Requirements
- A versioned artefact set: configuration, prompts or schemas, and the evaluation dataset
- Baseline measurements for quality, latency and cost before any change
- A release gate that blocks regressions rather than warning about them
- Documentation sufficient for another engineer to reproduce the evaluation
- A rollback procedure tested once before it is needed
Steps
- 1.Map the current workflow and identify the decision points where quality can be measured
- 2.Capture baseline metrics on live traffic samples and store them with the release record
- 3.Build or extend the evaluation dataset with edge cases drawn from real incidents
- 4.Implement the change behind a flag and run the evaluation harness against it
- 5.Roll out to a small cohort, compare against baseline and revert or proceed on evidence
- 6.Record the outcome and update the playbook with what the evaluation revealed
Enterprise & GCC Applications
- Global capability centres use Agent Memory & Context Engineering to standardise engineering practice across distributed teams, with shared evaluation and release gates rather than per-site conventions.
- Enterprise architecture groups apply the topic when defining reference platforms, so product teams inherit compliant defaults instead of rebuilding controls per project.
- Delivery leadership uses the associated metrics in quarterly reviews, replacing anecdotal quality claims with measured evaluation coverage and regression escape rates.
- Risk and audit functions rely on the artefacts the practice produces — versioned prompts, evaluation results, decision logs — as evidence during internal and external review.
Risks & Mitigations
Key Metrics
Trends & 2026 Outlook
Structured compaction schemas
Tiered memory architectures
Memory governance and deletion tooling
Long-context models reducing compaction need
Career Roles
Frequently Asked Questions
How large should the context window usage be?
Well below the model maximum. Leaving headroom keeps behaviour stable and cost predictable; filling the window trades reliability for nothing.
Do we need a vector database for memory?
Only if memory must be searched semantically at scale. Many agents need a session store and a small facts table, not a vector index.
How do we handle deletion requests?
Design the deletion path before launch: identify every store holding the data, including summaries, and verify removal end to end.
Should agents remember across users?
No. Memory must be scoped per user or per tenant, and cross-user leakage is a data breach rather than a bug.
What is the cheapest improvement?
Compaction with a structured summary schema, which typically cuts cost and improves long-session accuracy at the same time.
How do we test memory design?
With scripted long sessions containing commitments and constraint changes, then checking that later turns honour them.
What does a mature agent memory & context engineering practice look like?
It looks unremarkable: artefacts are versioned, changes arrive with evaluation evidence, thresholds block regressions, and a named owner reviews the metrics on a regular cadence. The visible behaviour is small frequent releases rather than occasional large ones, because small changes are what make attribution possible.
How do we start in an existing codebase without a rewrite?
Pick one workflow, instrument its baseline, and build a small evaluation set from real traffic and past incidents. Gate that single workflow first. Once the pattern is proven, extend it — retrofitting a whole estate at once usually stalls, while one gated workflow establishes the habit and the tooling.
What should we measure in the first thirty days?
Only what you can act on: a baseline for the workflow you chose, the leading signals that predict the outcome you care about, and the cost of running the current design. Resist adding dashboards nobody reads. Thirty days is enough to establish one gated workflow, one baseline and one caught regression, which is a stronger position than a broad but unmaintained measurement programme.
Which decisions belong in the platform rather than in each product team?
Anything that must be identical across the estate to be auditable: logging and trace format, secret handling, evaluation harness interfaces, flag mechanics and rollback paths. Behavioural decisions — what the system should do, what quality bar applies, which cases are unacceptable — belong with the product team that owns the outcome.
References & Resources
- Agent framework checkpointing documentation:Durable state and resumption patterns for long-running agents
- Memory architecture research:Episodic, semantic and working memory separation in agent systems
- Data retention guidance:Purpose limitation and erasure obligations applied to conversational state
- Observability practice for LLM applications:Tracing context size, latency and cost per step
Continue this lesson with a subscription
AI Engineering & AI-Native Software Development is part of the paid catalogue. You have read the free preview. A subscription opens the rest of this lesson, the classroom slides and the assessment questions.
- The full lesson for this topic and every other catalogue topic
- Every classroom slide deck and worked example
- All assessments, with a verifiable certificate on completion
The Free-To-Learn library stays open to everyone and is not affected by this.
