---
title: 'InMemorySessionService: Quick Prototyping and Ephemeral Multi-Turn State'
date: '2026-12-02T08:24:49+07:00'
description: 'What a SessionService is, how to set up InMemorySessionService for multi-turn conversations in local development, its data-loss caveats, how to test against it, and when to graduate to DatabaseSessionService or VertexAiSessionService.'
author: 'AI Assistant'
image: 'https://blog.redlinesoft.net/images/post/adk-in-memory-session-service-prototyping.jpg'
alt: 'A local development loop where conversations are held in process memory and vanish on restart'
tags: ['google-adk', 'sessions', 'prototyping', 'python']
---

Every stateful agent needs somewhere to keep the conversation, and the fastest way to start is also the most dangerous: a service object with no arguments, no configuration, and no setup — `InMemorySessionService()`. It is the right choice for the first afternoon of development and a serious incident if it is still there at launch, because everything it holds evaporates the moment the process restarts.

This article is about using that tool *well*: what a `SessionService` actually is, how `InMemorySessionService` powers multi-turn conversations in local dev, exactly what you lose when the process dies, how to build tests on it, and the signals that tell you it is time to move to `DatabaseSessionService` or `VertexAiSessionService`.

## Prerequisites

- ADK Python installed (`pip install google-adk`) and a working `LlmAgent`.
- Understanding of the `Runner` and that it commits each yielded event through a session service before your agent resumes.
- A model API key configured for the run examples (`GEMINI_API_KEY` or your provider's equivalent).

## 1. What a SessionService is

You rarely create or manage `Session` objects directly. A **`SessionService`** is the central manager for the entire lifecycle of conversation threads:

- **Start** — create a fresh `Session` when a user begins an interaction.
- **Resume** — retrieve a specific `Session` by ID so the agent continues where it left off.
- **Save** — append new `Event` objects to the history; this is also the mechanism through which session `state` gets updated.
- **List** — find the active threads for a given user and application.
- **Clean up** — delete a `Session` and its data when the conversation is over.

The `Runner` depends on one of these for every turn: it appends the incoming user message as the first event, then hands it every event the agent yields so `state_delta` and `artifact_delta` get committed. In other words, the session service is not a convenience wrapper — it *is* the persistence layer, and swapping it is a one-line change.

## 2. Setting up `InMemorySessionService`

Construction takes no arguments and requires nothing extra:

```python
from google.adk.sessions import InMemorySessionService

session_service = InMemorySessionService()
```

That is the entire setup. It stores session data directly in the application's memory, which is why the docs describe it as best for **quick development, local testing, examples, and scenarios where long-term persistence isn't required**.

Wire it into a `Runner` explicitly:

```python
from google.adk import Agent
from google.adk.runners import Runner

agent = Agent(
    name="assistant",
    model="gemini-flash-latest",
    instruction="You are a concise, helpful assistant.",
)

runner = Runner(
    agent=agent,
    app_name="proto_app",
    session_service=session_service,
)
```

> **Note:** construct the service once and share it across runners. A second `InMemorySessionService()` is a *different* store — conversations written by one will not be visible to the other, and you will spend an hour debugging a "missing" session that never existed in that process.

## 3. Multi-turn conversations in local dev

A conversation is one session, many turns. Create the session up front (or let `auto_create_session=True` do it), then feed each user message to the same `session_id`:

```python
import asyncio

from google.genai.types import Content, Part

APP_NAME = "proto_app"
USER_ID = "dev_user"

async def chat_turn(session_id: str, text: str) -> str:
    message = Content(role="user", parts=[Part(text=text)])
    reply = "(no response)"

    async for event in runner.run_async(
        user_id=USER_ID,
        session_id=session_id,
        new_message=message,
    ):
        if event.is_final_response() and event.content and event.content.parts:
            reply = event.content.parts[0].text or reply
    return reply


async def main() -> None:
    session = await session_service.create_session(
        app_name=APP_NAME,
        user_id=USER_ID,
        state={"turn_count": 0},
    )
    print("session:", session.id)

    print("user:", "My favourite project is Project Alpha.")
    print("bot :", await chat_turn(session.id, "My favourite project is Project Alpha."))

    print("user:", "What is my favourite project?")
    print("bot :", await chat_turn(session.id, "What is my favourite project?"))

asyncio.run(main())
```

Turn two works because the `Runner` loaded the *same* session: the first turn's events are in `session.events`, and anything written to `session.state` is still there. That is the whole persistence contract, visible in ten lines.

You can also inspect the stored result directly — useful when debugging what the agent actually committed:

```python
stored = await session_service.get_session(
    app_name=APP_NAME, user_id=USER_ID, session_id=session.id,
)
print(stored.state)    # e.g. {'turn_count': 1, 'last_greeting': '...'}
print(len(stored.events), "events")
```

### Saving values into state

The cheapest way to persist an agent's answer for a later turn is `output_key`:

```python
from google.adk import LlmAgent

greeter = LlmAgent(
    name="Greeter",
    model="gemini-flash-latest",
    instruction="Generate a short, friendly greeting.",
    output_key="last_greeting",   # written into the event's state_delta
)
```

For multi-key or scoped updates (`user:`, `app:`, `temp:`), construct an event with an explicit `EventActions(state_delta=...)` and append it via `session_service.append_event(session, event)`. Never mutate a `Session` you fetched from the service directly — that bypasses event tracking and can lose the change.

## 4. The data-loss caveats — read these twice

The documentation is unambiguous:

> **Persistence:** None. **All conversation data is lost if the application restarts.**

Concretely, that means:

- **Process restart = empty store.** Sessions, events, state, and any `user:`/`app:`-scoped keys written through this service are gone. There is no flush, no snapshot, no recovery.
- **Multiple processes do not share it.** Run two uvicorn workers or two containers and each has its own private store; a session created in worker A cannot be found in worker B, which surfaces as a `SessionNotFoundError`.
- **Ephemeral by design, including `user:` and `app:` prefixes.** Prefixes control *scope* (which sessions see the key), not durability. With an in-memory service, everything is non-durable.
- **Tests can bleed into each other** if they share one service instance — always isolate (next section).

None of this makes the service a bad tool. It makes it a **development** tool: zero setup, fast, and perfect for exercising control flow, prompts, and routing before infrastructure exists.

## 5. Using it in tests

`InMemorySessionService` is an excellent test double precisely because it implements the real interface. The recipe: a fresh instance per test, deterministic IDs, no network beyond the model call (or stub the model):

```python
import pytest

from google.adk.sessions import InMemorySessionService


@pytest.fixture
def session_service():
    """A clean store per test — no bleed between cases."""
    return InMemorySessionService()


async def test_second_turn_sees_first_turn_state(session_service):
    await session_service.create_session(
        app_name="test_app", user_id="u1", session_id="s1",
        state={"topic": "alpha"},
    )

    # ... run your agent/runner against session_service ...

    stored = await session_service.get_session(
        app_name="test_app", user_id="u1", session_id="s1",
    )
    assert stored.state["topic"] == "alpha"
    assert len(stored.events) >= 2   # user message + agent response


async def test_session_not_found_is_explicit(session_service):
    with pytest.raises(Exception) as exc:
        await session_service.get_session(
            app_name="test_app", user_id="u1", session_id="missing",
        )
    assert "missing" in str(exc).lower() or exc.type.__name__ == "SessionNotFoundError"
```

Two things worth asserting on in any session-service test suite, because they are exactly what changes when you swap implementations: **event ordering** and **state committed after each turn**. If those hold against `InMemorySessionService`, they will hold against a database-backed one too.

## 6. When to graduate

The migration trigger is not "we launched" — it is the first time you need a property in-memory cannot give you:

| You need… | Move to |
| --- | --- |
| Survive restarts, self-managed storage, row-level locking across replicas | `DatabaseSessionService` |
| Managed, scalable persistence on Google Cloud with Agent Platform | `VertexAiSessionService` |
| Local prototyping, unit tests, throwaway demos | stay on `InMemorySessionService` |

**`DatabaseSessionService`** connects to PostgreSQL, MySQL, or SQLite. It needs the `db` extra (`pip install google-adk[db]`) and an **async** driver — for SQLite the connection string must be `sqlite+aiosqlite:///./my_agent_data.db`, not plain `sqlite`. It uses in-process locking to serialize `append_event` per session plus row-level locking (`SELECT ... FOR UPDATE`) for PostgreSQL, MySQL, and MariaDB, so concurrent processes cannot corrupt a thread. Note also that the session schema changed in ADK Python v1.22.0 and requires a migration.

```python
from google.adk.sessions import DatabaseSessionService

db_url = "sqlite+aiosqlite:///./my_agent_data.db"
session_service = DatabaseSessionService(db_url=db_url)
```

**`VertexAiSessionService`** uses Google Cloud Agent Platform infrastructure. It requires a Google Cloud project, the `gcp` extra (`pip install google-adk[gcp]`), a configured storage bucket, an Agent Runtime resource, and — importantly — an `app_name` that is the **Reasoning Engine ID or name**, not an arbitrary label:

```python
from google.adk.sessions import VertexAiSessionService

PROJECT_ID = "your-gcp-project-id"
LOCATION = "us-central1"
REASONING_ENGINE_APP_NAME = (
    "projects/your-gcp-project-id/locations/us-central1/reasoningEngines/your-engine-id"
)

session_service = VertexAiSessionService(project=PROJECT_ID, location=LOCATION)
```

Because only the service construction changes, the rest of your code — `create_session`, `run_async`, `get_session`, `append_event` — stays identical. That is the payoff for depending on the interface rather than the implementation.

## 7. One error you will hit early

Running a session that does not exist raises **`SessionNotFoundError`** (it inherits from `ValueError` for backward compatibility). Common causes: a typo'd or expired `session_id`, or running before the session was created. Two fixes:

```python
# Option A: create it first (as in the chat example above)
session = await session_service.create_session(
    app_name=APP_NAME, user_id=USER_ID, session_id=session_id,
)

# Option B: let the Runner do it
runner = Runner(
    agent=agent,
    app_name=APP_NAME,
    session_service=session_service,
    auto_create_session=True,
)
```

## Checklist

- [ ] One shared `InMemorySessionService` instance per process — never one per call site.
- [ ] Sessions are created before the first `run_async`, or `auto_create_session=True` is set.
- [ ] All turns of a conversation reuse the same `app_name` + `user_id` + `session_id`.
- [ ] State changes go through `output_key` or `EventActions.state_delta`, not direct mutation of a fetched `Session`.
- [ ] Tests build a fresh service per test and assert on event ordering and committed state.
- [ ] You know that a restart wipes everything — no production traffic on this service.
- [ ] The migration target (`DatabaseSessionService` or `VertexAiSessionService`) is chosen *before* launch, with its extras installed and its async-driver or `app_name` requirements verified.

## Conclusion

`InMemorySessionService` is the shortest path from zero to a working multi-turn agent: no configuration, no infrastructure, and a faithful implementation of the interface you will use in production. Use it aggressively while prototyping — and treat its "lost on restart" semantics as a hard boundary rather than a default. When the conversation history starts to matter more than the code, swap the constructor, keep everything else, and let the interface do its job.

## References

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