Sessions, state and Memory Bank
Decide where each piece of an agent's data belongs. A session holds one conversation's events and state, state prefixes set how far a value reaches, and Memory Bank keeps facts across conversations.
Chapter 4Custom agentsLesson 3 of 8ShowHide
Chapter 4 of 7 in Google Cloud Professional Agentic Architect
- Sessions, state and Memory BankYou're here
Prerequisites: Building agents with ADK
Where does each piece of data belong?
Your support agent from the previous lesson now has real users. A customer
orders a lamp on Monday, asks you to ship it to their Lyon office, and picks
French as their reply language (the agent has a set_language tool for that).
On Thursday they come back. What should the agent still
know, and where should it have kept it?
Get this wrong in one direction and the agent feels broken: it forgets what was said three turns ago, or asks for the language again. Get it wrong in the other and it costs tokens on every call and keeps personal data it never needed. ADK gives you three places, and the decision is which one each value belongs in.
Sessions: one conversation
A is one conversation thread between a user and your agent. It holds two things:
- Events, the history: every user message, model response, tool call and tool result, in order. Each model call reads them, which is how the agent remembers what was said three turns ago.
- , a key-value scratchpad the agent
and your code read and write during the conversation, such as
order_id = "B-77".
A SessionService stores sessions. ADK ships three kinds:
| Service | Where sessions live | Use it for |
|---|---|---|
InMemorySessionService | The process's memory; lost on restart | Local development and tests |
DatabaseSessionService | A relational database you run (PostgreSQL, MySQL, SQLite) | Persistent sessions you manage |
VertexAiSessionService | Agent Platform Sessions, managed by Google Cloud | Production on Google Cloud without running a session store |
Agent Platform is Google Cloud's managed platform for building and running agents, and Agent Platform Sessions is its managed session store. In production, use a persistent service. An in-memory service on a platform that runs several copies of your app, such as Cloud Run (Google Cloud's serverless container service), loses the conversation whenever a request lands on another copy or a copy restarts. Agent Platform Sessions removes the need to run your own store; every session has a time to live (365 days unless you set one).
On Google Cloud, the natural home for DatabaseSessionService is Cloud
SQL (managed PostgreSQL or MySQL): it takes a database URL with an async
driver, so the same code runs on SQLite locally and Cloud SQL in production.
Firestore and Memorystore (managed Redis) are in scope too, mainly as data
stores your tools read and write, such as a customer profile in Firestore
or a cache in Memorystore. Neither is one of the three built-in session
services above: ADK for Java offers a Firestore session service as a separate
integration, but the ADK for Python package ships none, and no built-in session service runs
on Memorystore.
State scopes: how far a value reaches
The prefix on a state key sets its scope:
| Key | Scope | Example |
|---|---|---|
order_id (no prefix) | This session only | The order being discussed |
user:language | Every session of this user, in this app | A preference the user set |
app:support_hours | Every user and session of the app | A global setting |
temp:api_raw | This invocation only (one turn); never persisted | A scratch value between two tools |
Your code reads and writes one merged state; the session service stores each
key where its prefix says. A tool writes state through its tool_context:
from google.adk.tools.tool_context import ToolContext
def set_language(language: str, tool_context: ToolContext) -> dict:
"""Sets the language the agent replies in, for all of this user's conversations.
Args:
language: An ISO language code, for example "fr".
"""
tool_context.state["user:language"] = language
return {"status": "success", "language": language}Scopes beyond the current session persist only if the session service does:
with InMemorySessionService, a user: key disappears on restart along with
everything else. ADK's state guide says these scopes persist with the database and Vertex AI
session services, but ADK's own tests of shared user: and app: state cover
DatabaseSessionService only, so on Agent Platform Sessions check that a
user: key written in one session reads back in a new one before you rely on
it.
Every user of the store should see the same current discount code, which an admin tool updates. Which key fits?
Try it: which values survive a new session?
The app is drawn as a building. Each user has an apartment, each session is a
room in it, and the agent works at a desk in the current room. A key's prefix
decides where the tool's note goes: the desk whiteboard (temp:), the room
wall (no prefix), the apartment fridge (user:) or the lobby noticeboard
(app:). Whatever the agent can read right now is lit.
Before you press anything, predict: a tool writes language = "fr" once with no
prefix and once as user:language. In a new session for the same user, which
of the two does the agent still read? And for a different user?
Stick both notes, open a new session, then switch users. Then compare restarts.
In the brick building (DatabaseSessionService), stick a note on the fridge
and press Restart process. Then switch to the tent (InMemorySessionService),
which starts the exercise again with an empty store. Stick the same note and
restart again. Scope decides who reads a key, but only a persistent service
keeps it across a restart.
Explain it in one sentence: why is a temp: key gone on the very next turn of
the same session, while a user: key reaches a session that did not exist when
it was written?
Memory: what lasts across conversations
A session ends. Some of what the user said is worth keeping: where they work, what they bought, what went wrong last time. That is long-term memory, and ADK reaches it through a memory service. Session and state are short-term memory for one conversation; memory is a searchable store across many.
is Agent Platform's managed long-term
memory, and ADK connects to it with VertexAiMemoryBankService. It does not
store transcripts. It:
- Extracts the meaningful facts from a conversation with an LLM, and consolidates them with what it already holds, so a changed fact updates a memory instead of piling up duplicates.
- Isolates memories per scope, such as the app (or agent) and the user, so one user's memories never reach another's conversation. Every session therefore needs a user id.
- Retrieves either all memories for a scope or only the ones most relevant to the current message.
You can steer what it extracts with your own topics and few-shot examples, let the agent write a memory directly when it decides one is worth saving, and set a time to live on memories. A default time to live is counted from each creation or update, so a memory that consolidation keeps updating stays longer than one written once.
Follow the same customer from Monday to Thursday. Before you step into session 2,
predict whether order_id is still there, then watch which values cross into
the new session and which facts Memory Bank brings back.
So on Thursday the agent starts a new, empty conversation, yet still replies in
French (a user: key its own tool wrote) and offers the Lyon office (a fact
Memory Bank extracted and recalled). The order id from Monday is not in the new session, as it
should be. It has not been deleted: Monday's session is still stored, and your
app can load and resume it until you delete it or its time to live expires.
Wire Memory Bank into an ADK agent
Three pieces, each a choice:
- The service. Pass a
VertexAiMemoryBankServiceto theRunner, or startadk webwith--memory_service_uri="agentengine://<instance_id>". The instance is either the Memory Bank built into an Agent Runtime instance, or a standalone Memory Bank instance with no deployed runtime, which can live in a multi-region (us,eu) orglobal. The difference matters for lifecycle: deleting an Agent Runtime instance also deletes the memories in its built-in Memory Bank, while a standalone instance outlives any one deployment. Agent Runtime is Agent Platform's managed runtime for agents; it was formerly called Agent Engine, which is why the parameter isagent_engine_id. - When to save. Memories are generated when you send conversation events to
the service. Google recommends
add_events_to_memoryin an after-agent callback to send the latest events after each turn.add_session_to_memorysends the whole session, so call it once, at the end of a session, or the same events are processed again on every turn. - How to recall.
preload_memoryretrieves relevant memories at the start of every turn;load_memoryis a tool the model calls only when it decides memory would help. Preload is predictable and costs a lookup on every model call in a turn; load saves lookups but depends on the model asking.
from google.adk.agents import LlmAgent
from google.adk.agents.callback_context import CallbackContext
from google.adk.memory import VertexAiMemoryBankService
from google.adk.runners import Runner
from google.adk.sessions import VertexAiSessionService
from google.adk.tools import preload_memory
async def save_to_memory(callback_context: CallbackContext):
# Send only the latest events, so earlier turns aren't processed again.
await callback_context.add_events_to_memory(
events=callback_context.session.events[-5:]
)
root_agent = LlmAgent(
name="support_agent",
model="gemini-flash-latest",
instruction="Help customers with orders. Use what you remember about them.",
tools=[preload_memory],
after_agent_callback=save_to_memory,
)
runner = Runner(
agent=root_agent,
app_name="store-support",
session_service=VertexAiSessionService(
project="PROJECT_ID", location="LOCATION", agent_engine_id="AGENT_RUNTIME_ID"
),
memory_service=VertexAiMemoryBankService(
project="PROJECT_ID", location="LOCATION", agent_engine_id="AGENT_RUNTIME_ID"
),
)The Runner's session service creates and loads each session by app_name,
user_id and session_id (the ids you pass to run_async), and its memory
service is what add_events_to_memory and the memory tools talk to. An
after-agent callback runs after every agent run, so this agent sends its latest
events to Memory Bank after every turn, and Memory Bank consolidates them with
what it already holds. To save once per conversation instead, call
add_session_to_memory when your app decides the conversation is over.
Choosing the place
- Needed only for this turn?
temp:state. - Part of this conversation? The session's events and plain state.
- A setting your app owns, the same every time?
user:(orapp:) state on a persistent session service that shares those scopes (verified onDatabaseSessionService). Your code writes and reads it exactly. - A fact users mention that you did not model as a field? Memory Bank, which extracts it, consolidates it and recalls it when relevant.
- Everything, pasted into the prompt? Never. Every token in the prompt costs latency and money on every call, distracts the model and spreads personal data; Context engineering at scale measures it.
Sources
Show 9 sourcesHide sources
| Source | Publisher | What it supports |
|---|---|---|
| State (opens in a new tab) | Google, Agent Development Kit documentation | state prefixes: none, user:, app:, temp:; persistence depends on the session service |
| Agent Development Kit, adk-python source, src/google/adk/sessions/database_session_service.py | DatabaseSessionService takes a SQLAlchemy database URL with an async driver, such as PostgreSQL, MySQL or SQLite | |
| Session State Management using Firestore (opens in a new tab) | Google, Agent Development Kit documentation | a Firestore session service for ADK Java, shipped as a separate package |
| Session (opens in a new tab) | Google, Agent Development Kit documentation | events and state; InMemorySessionService, VertexAiSessionService, DatabaseSessionService |
| Memory (opens in a new tab) | Google, Agent Development Kit documentation | MemoryService; VertexAiMemoryBankService; add_session_to_memory; preload_memory and load_memory; the after-agent callback pattern; memory_service_uri |
| Agent Platform Memory Bank (opens in a new tab) | Google Cloud | extraction, consolidation, scopes and user ids, retrieval modes, topics and few-shot examples, memory time to live; last updated 2026-11-12 |
| Use Memory Bank with ADK (opens in a new tab) | Google Cloud | retrieved 2026-12-02: callback_context.add_events_to_memory sends a subset of events you select and is recommended for incremental processing, for example after each turn; add_session_to_memory sends all events and should be called once at the end of a session so the same events are not processed more than once; example callback sends session.events[-5:] |
| Set up Memory Bank (opens in a new tab) | Google Cloud | retrieved 2026-12-02: standalone Memory Bank instances without a deployed runtime; multi-regional us and eu and global endpoints; deleting an Agent Runtime instance also deletes its memories when using built-in Memory Bank |
| Manage sessions with ADK (opens in a new tab) | Google Cloud | Agent Platform Sessions; VertexAiSessionService; every session expires, default time to live 365 days |
Suggested videos
Show 2 videosHide videos
How to add short-term memory to your AI agent (Sessions & State Explained) (opens YouTube in a new tab)
Explains ADK sessions, events and state, the first half of the lesson.
Note: State prefixes (user:, app:, temp:) aren't covered in detail.
AI agent long-term memory with memory bank (opens YouTube in a new tab)
Short, current Memory Bank walkthrough for keeping facts across conversations.
Review
What do a session, session state and long-term memory each hold?
Check yourself
Your agent has a set_reply_language tool that the model calls when a user picks a language. The choice must apply, exactly, in all of that user's future conversations. Where should the tool write it?