---
title: 'State vs Memory vs Sessions: Deconstructing Persistence in ADK'
date: '2026-12-02T08:24:49+07:00'
description: 'A conceptual map of ADK persistence: sessions as conversation containers, state as a scoped key-value scratchpad, memory as cross-session knowledge, and artifacts for bulk data — with a decision table for when to use each.'
author: 'AI Assistant'
image: 'https://blog.redlinesoft.net/images/post/adk-state-vs-memory-vs-sessions.jpg'
alt: 'Four nested storage layers around an agent: session, state, memory, and artifacts'
tags: ['google-adk', 'sessions', 'state', 'memory', 'architecture']
---

Ask three engineers where a user's preferred language should live in an ADK app and you will get three answers: "in state, `user:` prefix," "in memory, so it survives new sessions," and "in the session, obviously." All three are plausible, and only one is right for a given requirement — which is the tell that these three words are doing too much work.

ADK splits persistence into four distinct mechanisms with different lifetimes, different scopes, and different read paths: **sessions** (the conversation container), **state** (a scoped key-value store inside a session), **memory** (searchable knowledge spanning sessions), and **artifacts** (bulk binary data). Confusing them produces apps that forget everything, remember too much, or quietly lose data on redeploy. This article deconstructs each one and gives you a decision table you can apply without re-reading the docs.

## Prerequisites

- ADK installed (`pip install google-adk`) and a `Runner` you have run at least once.
- Basic familiarity with `InMemorySessionService` and the event loop.
- No prior assumption about which storage is "the" storage — that is the point.

## 1. Sessions: the conversation container

A `Session` (`google.adk.sessions.Session`) represents **one conversation thread** between a user and your agent. Its properties are the whole persistence story in miniature:

- **`id`, `app_name`, `userId`** — identity: which conversation, which application, which user.
- **`events`** — the chronological list of everything that happened: user messages, agent responses, tool calls, state changes.
- **`state`** — the scratchpad for *this* conversation (next section).
- **`last_update_time`** — when the thread last moved.

You do not create `Session` objects by hand; a **`SessionService`** owns the lifecycle — creating new threads, resuming existing ones by ID, appending events, listing, and deleting. That service choice determines *persistence*:

| Implementation | Persistence | Best for |
| --- | --- | --- |
| `InMemorySessionService` | **None** — lost on restart | Quick development, local testing, examples |
| `DatabaseSessionService` | Yes — survives restarts | Self-managed relational storage (PostgreSQL, MySQL, SQLite) |
| `VertexAiSessionService` | Yes — managed via Agent Platform | Production on Google Cloud |

The mental model: **the session is the unit of continuity.** Everything scoped to "this conversation" lives inside it, and everything inside it is replayable because it is an ordered event log.

## 2. State: the session's scoped scratchpad

`session.state` is a dictionary of key-value pairs holding what the agent needs to track *during* the conversation — a shopping cart, a booking step, an authentication flag, a turn counter.

Three characteristics define it:

- **Serializable values only.** Keys are strings; values must be storable and reloadable by the `SessionService`. No class instances, no functions, no open connections — store an identifier and reconstruct the object elsewhere.
- **Mutability is expected.** State is designed to change as the conversation evolves.
- **Persistence follows the session service.** With `InMemorySessionService`, state dies on restart; with `Database` or `VertexAI`, it survives.

### The prefixes are the API

The prefix on a key decides its scope and lifetime:

| Prefix | Scope | Typical use |
| --- | --- | --- |
| *(none)* | Current session only | `current_booking_step`, `needs_clarification` |
| `user:` | All sessions for one user, within an app | `user:theme`, `user:name` |
| `app:` | All users and sessions for this app | `app:api_endpoint`, shared templates |
| `temp:` | **Current invocation only**, discarded after | Intermediate results, per-request scratch |

That `temp:` row is the one people miss: it is scoped to a single *invocation* — everything from the agent receiving a user's input to producing the final output for that input — and is discarded afterwards. When a parent agent calls a sub-agent, the `InvocationContext` (and therefore the `temp:` scope) is shared across the whole chain.

### How state actually gets written

State must always be updated **as part of appending an event**, so the change is tracked, persisted, and thread-safe. Two supported routes:

1. **`output_key` on an `LlmAgent`** — the agent's final text response is written into the event's `state_delta` automatically.
2. **An explicit `EventActions(state_delta={...})`** on an event you construct, for multi-key, non-string, or scoped updates.

```python
from google.adk.events import Event, EventActions

changes = {
    "task_status": "active",                     # session scope
    "user:login_count": login_count + 1,         # user scope
    "temp:validation_needed": True,              # discarded after this invocation
}
event = Event(invocation_id=..., author="system",
              actions=EventActions(state_delta=changes))
await session_service.append_event(session, event)
```

> **Warning:** never write to a `Session` object you fetched from the `SessionService` directly (`my_session.state[...] = ...`). That bypasses ADK's event tracking and can lose data. Modify state on the `Context` you were handed, or emit a `state_delta`.

### Reading state in instructions

`LlmAgent` instructions support `{key}` templating: the framework substitutes the value from session state before calling the model. Use `{key?}` for keys that may be absent, and an `InstructionProvider` function when your instruction contains literal curly braces (JSON examples, for instance).

## 3. Memory: knowledge that outlives the conversation

If state is short-term memory for one chat, **memory is a searchable archive across many chats** — or across external sources entirely. It is managed by a **`MemoryService`**, whose interface supports:

- **`add_session_to_memory`** — ingest a completed session; the natural "remember this conversation" call.
- **`add_events_to_memory`** — ingest a delta of events (say, the latest turn) without re-ingesting the whole session.
- **`add_memory`** — add explicit `MemoryEntry` objects for fine-grained facts from other sources.
- **`search_memory`** — retrieve relevant snippets by query.

(`add_events_to_memory` and `add_memory` are optional — confirm your implementation supports them.)

Three implementations cover very different needs:

| | `InMemoryMemoryService` | `VertexAiMemoryBankService` | `VertexAiRagMemoryService` |
| --- | --- | --- | --- |
| Persistence | None — lost on restart | Managed by Agent Platform | Stored in Knowledge Engine |
| Extraction | Stores full conversation | LLM extracts and consolidates meaningful memories | Stores full conversation |
| Search | Basic keyword matching | Semantic search | Vector similarity |
| Setup | None — it's the default | Low — needs an Agent Runtime | Medium — needs a RAG corpus |

Agents *read* memory through tools — `load_memory` retrieves when the agent decides it would help, `preload_memory` fetches automatically at the start of a turn — or from a custom tool via `tool_context.search_memory(query)`. Writing is explicit: a common pattern is an `after_agent_callback` that calls `callback_context.add_session_to_memory()`.

The critical distinction: **memory ingestion is a decision, not a side effect.** Nothing is remembered until you push it, and what is remembered is only as good as the extraction step.

## 4. Artifacts: the fourth mechanism nobody mentions

State and memory are text-shaped. When the payload is a PDF, an image, an audio clip, or a generated report, you want **artifacts** — binary blobs stored by the `ArtifactService` (`InMemoryArtifactService`, `GcsArtifactService`) and referenced by identifier. The `Runner` confirms the write through the `artifact_delta` on the event, exactly as it confirms state changes through `state_delta`.

Artifacts are also the correct answer for *large* values that would otherwise tempt you into stuffing state: store the blob, keep the reference in state.

## 5. The decision table

| You need to… | Use |
| --- | --- |
| Keep the ordered record of one conversation | **Session** (`events`) |
| Track a step, flag, or small value for this conversation | **State**, unprefixed key |
| Share a preference across all of a user's conversations | **State**, `user:` prefix |
| Share a setting across every user of the app | **State**, `app:` prefix |
| Pass scratch data between calls in one request | **State**, `temp:` prefix |
| Inject a value into an agent's prompt | **State** + `{key}` templating |
| Save an agent's final answer for downstream steps | **State** + `output_key` |
| Recall facts from *past* conversations | **Memory** (`add_session_to_memory` + `load_memory`) |
| Let the agent search a knowledge base on demand | **Memory** (`search_memory` in a tool) |
| Store a file, image, or any bulk/binary payload | **Artifacts** |
| Move a value from one node to its successor | **Node `output`** (not state at all) |
| Survive an application restart | Anything but `InMemory*` services |

Two rules of thumb collapse the table into a habit:

1. **If only the next step needs it, it is not state — it is an edge value.** State is for what must outlive a node: read by tools, callbacks, or `{key}` templating, and scoped by prefix.
2. **If it must survive a restart, the service decides, not the key.** Prefixes control *scope*; the `SessionService`/`MemoryService` implementation controls *durability*.

## 6. How the four compose

The `Runner` ties it together in one loop: it receives a user query, appends it as an event, runs the agent, and for each yielded event commits `state_delta` through the `SessionService` and confirms `artifact_delta` against the `ArtifactService` — *before* the agent logic resumes. Memory is the odd one out: it is ingested deliberately, not automatically.

So the full picture of one turn:

```
user input
   └─> Session (event appended)
         └─> agent runs, reads/writes State via Context
               ├─ state_delta  -> committed to Session by Runner
               ├─ artifact_delta -> confirmed against ArtifactService
               └─ yields events -> user sees them
   (later, explicit) Session -> MemoryService.add_session_to_memory
   (later, explicit) agent tool -> MemoryService.search_memory
```

## Checklist

- [ ] Every value has an intentional home: session, state (with the right prefix), memory, artifact, or edge.
- [ ] State values are serializable — no objects, no connections, no functions.
- [ ] All state writes go through `output_key` or `EventActions.state_delta`, never through a fetched `Session` object.
- [ ] `temp:` is used for invocation-scoped scratch and nothing longer-lived hides there.
- [ ] Memory ingestion is wired explicitly (callback or service call), not assumed.
- [ ] Bulk payloads live in artifacts with a reference in state.
- [ ] The chosen `SessionService` matches the durability requirement — `InMemory*` is a development choice, not a default you ship.
- [ ] `{key}` placeholders in instructions exist in state (or use `{key?}`).

## Conclusion

Sessions give you continuity, state gives you scoped working memory, memory gives you a searchable past, and artifacts give you somewhere to put things that do not fit in a dictionary. They are not competing stores — they are four layers with different lifetimes, and the craft is in assigning each value to the layer whose lifetime matches the requirement. Get that assignment right and your agent remembers what it should, forgets what it must, and never loses a session to a redeploy.

## References

- https://adk.dev/sessions/
- https://adk.dev/sessions/state/
- https://adk.dev/sessions/memory/
- https://adk.dev/sessions/session/
- https://adk.dev/runtime/event-loop/
- https://adk.dev/artifacts/
