ADK sessions, state, memory and artifacts compared
Put each piece of agent data in the right place: session history, temporary context, state, long-term memory or artifacts, and choose in-memory or persistent services.
By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.
In short
ADK keeps agent data in five places: session events (the conversation history), state (small key-value facts), temp state (values for one invocation only), memory (searchable knowledge across past sessions) and artifacts (named, versioned files). State keys use prefixes to set scope: no prefix for this session, user: for all of one user's sessions, app: for every user, temp: for the current invocation. In-memory services lose everything on restart; database or managed services keep it.
Explained simply
An agent needs to remember things, but not everything belongs in the same place. ADK gives you separate stores with separate jobs. The session holds the conversation itself: every message, tool call and answer, in order. That list is called the history.
State is a small dictionary of facts attached to a session, such as the ticket the user is asking about or their plan. The agent's instruction can read state values, and tools can write them. A key's prefix sets who shares it: no prefix for this conversation only, user: for every conversation of that user, app: for everyone, and temp: for the current request only.
Memory is different. It is a searchable store of knowledge from past conversations, used when a user expects the agent to remember last week's chat. Artifacts are files, such as a generated report or an uploaded image, saved by name with version numbers.
Each store has an in-memory version for development, which forgets everything when the program stops, and persistent versions backed by a database or a Google Cloud service. Real deployments with more than one server need the persistent kind.
Press Play on a diagram to walk through it one step at a time.
- Session events
- Messages and tool calls
- Per session, ordered
- State
- topic: this session
- user:plan: all sessions of a user
- app:banner: every user
- Temp state
- temp:last_status
- Dropped after the invocation
- Memory
- Searchable past sessions
- load_memory or preload_memory tools
- Artifacts
- Files and binary data
- Versioned from 0
- user: prefix for cross-session
- No setup
- Lost on restart
- One process only
- Tests and quick demos
- Needs google-adk[db]
- Async driver URL, e.g. postgresql+asyncpg
- Shared by many instances
- You own backups and retention
- Managed by Google Cloud
- Needs an Agent Runtime resource
- Paid service
- Pairs with Memory Bank
- Tool to Runner: Sets current_ticket in tool_context.state1Sets current_ticket in tool_context.state
- Runner to Session service: append_event with state_delta2append_event with state_delta
- Session service to Runner: Delta applied by prefix, temp: dropped3Delta applied by prefix, temp: dropped
- Runner to Your code: Event yielded with actions.state_delta4Event yielded with actions.state_delta
In depth
History versus state
History is the full list of events and grows with every turn. ADK sends it to the model so the conversation makes sense. State is a compact summary of facts you want to look up quickly or inject into instructions, such as current_ticket or user:language. Do not copy the whole history into state, and do not rely on the model to find a fact buried in a long history when a state key would do.
There are three supported ways to change state. Set output_key on an agent to save its final reply under that key. Write to context.state inside a tool or callback. Or append an event whose actions carry a state_delta. All three go through events, so changes are recorded, persisted and replayable. Editing session.state on a session you fetched yourself skips all of that.
- output_key="last_answer" saves the final reply
- tool_context.state["k"] = v inside tools
- EventActions(state_delta={...}) for system events
- Read-only: sessions fetched with get_session
Prefixes and scopes
The prefix decides scope and lifetime. A plain key belongs to one session. A user: key is shared by all sessions of that user in that app: set user:language once and every new session for that user starts with it. An app: key is shared by every user, so it suits things like a feature flag, never personal data. A temp: key lives for one invocation and is never saved, which suits intermediate values passed between steps of one request.
In instructions, {current_ticket} inserts a value and raises an error if the key is missing; {user:language?} inserts it only when present. Persistence still depends on the service: with InMemorySessionService even user: and app: values vanish on restart.
- 1app:
Every user and session of the app
- 2user:
Every session of one user
- 3No prefix
One session
- 4temp:
One invocation, never saved
When memory is needed
Memory answers the question: what did this user tell us in earlier conversations? You add a finished session with memory_service.add_session_to_memory(session), and the agent searches it with the load_memory tool, which it calls when it decides to, or preload_memory, which searches at the start of each turn. InMemoryMemoryService does simple keyword matching for development. VertexAiMemoryBankService uses Memory Bank, a managed and paid Google Cloud service that needs an Agent Runtime instance.
A bounded support assistant often does not need memory. Ticket data lives in the ticket system and is fetched by a tool. Add memory only for a clear requirement, and remember it becomes another store of personal data to retain and delete.
Storing files as artifacts
Artifacts are for binary or large data: a PDF export, an image, a CSV. Inside a tool, await tool_context.save_artifact(filename="summary.txt", artifact=types.Part(text=...)) saves a new version and returns its number, starting at 0. load_artifact returns the latest version or a given one. A plain filename is scoped to the session; a user: prefix, such as user:profile.png, makes it available in every session of that user.
The runner needs an artifact_service, otherwise these calls raise an error. InMemoryArtifactService suits tests, FileArtifactService stores files on local disk and GcsArtifactService uses a Cloud Storage bucket.
- save_artifact returns the version number
- load_artifact(filename, version=None) for latest
- user: filename prefix for cross-session files
- Keep state small; put files in artifacts
In-memory versus persistent session services
InMemorySessionService keeps sessions in a Python dictionary. It needs no setup and is perfect for tests, but it is lost on restart and cannot be shared by two processes. DatabaseSessionService stores sessions in a relational database through SQLAlchemy. Install google-adk[db] and pass an async URL such as sqlite+aiosqlite:///./sessions.db or postgresql+asyncpg://user:pass@db.example.com/adk. VertexAiSessionService stores sessions in Google Cloud's managed service and needs an Agent Runtime resource.
With several instances behind a load balancer, any instance may receive the next turn, so all of them must read the same store. That means a database or managed service. adk web, by contrast, defaults to a local SQLite file per agent, which is why its sessions survive restarts.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Separate history from state~35m
- 2Use state key prefixes and scopes~35m
- 3Know when memory is needed~35m
- 4Store files as artifacts~35m
- 5Compare in-memory and database session services~35m
Key points
- History is the list of events; state is a small dictionary of facts derived from it.
- Change state through output_key, context.state in tools and callbacks, or an event's state_delta, never by editing a fetched session.
- user: and app: state is shared across sessions, so never store one user's private data under app:.
- Memory is for recalling past conversations; most bounded agents do not need it at first.
- Artifacts hold files; save them with context.save_artifact and an artifact service on the runner.
Key terms
Tap a card to flip it. 0/5 known
Examples
from google.adk.tools import ToolContext
def remember_ticket(ticket_id: str, tool_context: ToolContext) -> dict:
"""Remember the ticket the user is asking about."""
tool_context.state["current_ticket"] = ticket_id # this session
tool_context.state["temp:lookup_ok"] = True # this invocation only
return {"saved": ticket_id}ADK fills tool_context automatically and records the change as a state_delta.
Seeing each scope in action
Create a session for user-a with three keys, then a second session for user-a and one for user-b. Expected evidence: user-a's new session contains user:plan and app:banner but not cart; user-b's session contains only app:banner. This is the clearest way to learn the scopes, and it runs fully in memory, so there is nothing to clean up.
svc = InMemorySessionService()
await svc.create_session(app_name="x", user_id="user-a",
state={"user:plan": "pro", "app:banner": "hi", "cart": 1})
a2 = await svc.create_session(app_name="x", user_id="user-a")
b1 = await svc.create_session(app_name="x", user_id="user-b")
print(a2.state) # {'user:plan': 'pro', 'app:banner': 'hi'}
print(b1.state) # {'app:banner': 'hi'}Switching to a persistent database store
For local persistence, install the db extra and point DatabaseSessionService at SQLite with the async driver. Step 1: install. Step 2: create the service with the URL. Step 3: pass it to the runner. Expected evidence: stop and restart the script, then get_session with the old ID still returns the history. Cleanup: delete sessions.db. In production use PostgreSQL with asyncpg and managed credentials.
# pip install "google-adk[db]==2.15.1" aiosqlite
from google.adk.sessions import DatabaseSessionService
sessions = DatabaseSessionService(db_url="sqlite+aiosqlite:///./sessions.db")
runner = Runner(app=app, session_service=sessions)Quick reference
- No prefix: this session; user: all of a user's sessions; app: everyone; temp: this invocation
- Change state via output_key, context.state or state_delta, never by editing a fetched session
- {key} in instructions is required; {key?} is optional
- Files go in artifacts: await tool_context.save_artifact(filename, part) returns a version
- Memory: add_session_to_memory, then load_memory or preload_memory tools
- DatabaseSessionService needs google-adk[db] and an async URL like sqlite+aiosqlite:///
- More than one instance? Use a shared persistent session service
Common mistakes
- Writing session.state[...] on a session fetched from the service; the change is not recorded as an event and may not persist.
- Storing large documents in state instead of artifacts, which bloats every session read.
- Using DatabaseSessionService with a sync URL such as sqlite:/// instead of sqlite+aiosqlite:///.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Classify where each item belongs: the user's preferred language, the ticket ID being discussed now, a CSV export, an intermediate score used once in a request, and the full chat log.
- Exercise 2medium
Write a tool that stores the ticket the user asked about in session state and returns it, then run it and confirm the value appears in a fresh get_session.
- Exercise 3hard
Show that InMemorySessionService loses data on restart and DatabaseSessionService with SQLite keeps it.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between state and memory?
- State is a small dictionary tied to a session, user or app that you read and write directly. Memory is a searchable store of past conversations the agent queries with a tool.
- Are user: values deleted when I delete a session?
- No. User and app state are stored apart from any one session, so deleting a session leaves them in place. Remove them separately in your retention process.
- Can I use Redis or Firestore for sessions?
- You can implement BaseSessionService for any store, and some community packages exist. Check that your implementation handles the 2.x event fields and prefix scopes.