---
title: "Managing Session Lifecycle: Creation, Retrieval, Archival, and Deletion"
date: "2026-12-03T08:32:03+07:00"
description: "A practical tour of the ADK session lifecycle — the five SessionService operations, how the Runner drives each turn, SessionNotFoundError recovery, and patterns for listing, archiving, and deleting conversations."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-session-lifecycle-management.jpg"
alt: "A circular lifecycle diagram of a conversation thread from creation to deletion"
tags: ['google-adk', 'sessions', 'lifecycle', 'runner', 'retention']
---

Every ADK conversation is born, resumed, appended to, listed, and — eventually — deleted. Miss one step and you get the classic symptoms: a `SessionNotFoundError` on the user's second message, a history page that loads sessions with no events in them, or a database that grows forever because nobody ever called `delete_session`.

The lifecycle is only five operations plus a loop the `Runner` runs for you. This tutorial walks the loop end to end, then handles the three operational tasks — retrieval, archival, and deletion — with the exact call shapes ADK expects.

## Prerequisites

- ADK installed (`pip install google-adk`) and a `Runner` you have executed once.
- Familiarity with `InMemorySessionService`; the same calls apply to `DatabaseSessionService` and `VertexAiSessionService`.
- No assumption that "archival" is a framework primitive — you will build it from `list_sessions` and `delete_session`.

## 1. The loop the Runner runs for you

A single turn against a session follows seven documented steps:

```
1. Start or resume   -> create_session(...) or reuse an existing session_id
2. Context provided  -> Runner fetches the Session (state + events) from the service
3. Agent processing  -> agent reads state/events, decides on a response
4. Response packaged -> Runner wraps the output as an Event
5. Save interaction  -> session_service.append_event(session, event)
                        applies state_delta, appends history, bumps last_update_time
6. Ready for next    -> response reaches the user; cycle restarts at step 1
7. End conversation  -> delete_session(...) when the data is no longer needed
```

Step 5 is the heartbeat: **state is only ever committed through `append_event`**, which is why writing to a fetched `Session` object directly loses data. Your application owns steps 1 and 7; the `Runner` owns 2 through 6.

## 2. The five operations

| Operation | Signature (Python) | Purpose |
| --- | --- | --- |
| `create_session` | `(*, app_name, user_id, state=None, session_id=None) -> Session` | Start a new conversation; optional id and initial state |
| `get_session` | `(*, app_name, user_id, session_id, config=None) -> Session \| None` | Resume by id; `None` if it does not exist |
| `list_sessions` | `(*, app_name, user_id=None) -> ListSessionsResponse` | Enumerate a user's (or app's) sessions |
| `delete_session` | `(*, app_name, user_id, session_id) -> None` | Remove a conversation and its data |
| `append_event` | `(session, event) -> Event` | Commit an event, its `state_delta`, and `last_update_time` |

All keyword-only, all present on every implementation — the lifecycle code you write once works across in-memory, database, and Vertex AI backends.

## 3. Create, resume, and cheap retrieval

```python
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.sessions.base_session_service import GetSessionConfig

session_service = InMemorySessionService()

# 1. Create — the id comes back on the Session
session = await session_service.create_session(
    app_name="shop_app",
    user_id="u_123",
    state={"cart": [], "step": "browse"},
)
session_id = session.id

# 2. Resume later — full history and state
same = await session_service.get_session(
    app_name="shop_app", user_id="u_123", session_id=session_id
)

# 3. Cheap read — only the most recent events, for a sidebar or preview
recent = await session_service.get_session(
    app_name="shop_app",
    user_id="u_123",
    session_id=session_id,
    config=GetSessionConfig(num_recent_events=20),
)

# 4. List — ids and metadata only; events and state are NOT attached
page = await session_service.list_sessions(app_name="shop_app", user_id="u_123")
for listed in page.sessions:
    print(listed.id, listed.last_update_time)
```

The subtle trap is in step 4: `list_sessions` returns `Session` objects **without** events or state. Any per-session detail you display needs a follow-up `get_session` — or `GetSessionConfig(num_recent_events=N)` to keep the payload small.

## 4. Recovering from `SessionNotFoundError`

When a `Runner` is asked to continue a session that does not exist — an expired id, a deleted row, a client replaying an old URL — it raises `SessionNotFoundError`, which inherits from `ValueError` for backward compatibility.

| Cause | Fix |
| --- | --- |
| Session never created in this environment | Call `create_session(...)` first and store the returned id |
| Id from a wiped in-memory store after restart | Use a persistent `SessionService`, or recreate |
| Runner constructed without a session guard | Pass `auto_create_session=True` to `Runner` |

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

runner = Runner(
    agent=agent,
    app_name="shop_app",
    session_service=session_service,
    auto_create_session=True,   # missing id -> create instead of raising
)
```

The defensive pattern for user-supplied ids: try `get_session`, and on `None` (or a caught `SessionNotFoundError` from the `Runner`) fall back to `create_session` with the same id — the service assigns it only when it is free.

## 5. Archival and deletion

ADK has no "archive" verb; archival is a policy you compose from the operations above:

| Retention need | Compose |
| --- | --- |
| Show a user their chat list | `list_sessions` (+ `get_session` per item for detail) |
| Keep only recent context on resume | `get_session(config=GetSessionConfig(num_recent_events=...))` |
| Detect idle conversations | Compare `session.last_update_time` against your threshold |
| Archive finished conversations | Export, then `delete_session` (or keep rows in a DB with your own TTL) |
| Enforce a hard retention window | `list_sessions` → filter by `last_update_time` → `delete_session` |
| Survive restarts | Choose a persistent `SessionService` in the first place |

```python
import time

from google.adk.sessions import InMemorySessionService

session_service = InMemorySessionService()
THIRTY_DAYS = 30 * 24 * 60 * 60


async def purge_stale_sessions(app_name: str, user_id: str) -> int:
    """Delete conversations untouched for 30 days. Returns count removed."""
    page = await session_service.list_sessions(app_name=app_name, user_id=user_id)
    removed = 0
    now = time.time()
    for listed in page.sessions:
        if now - listed.last_update_time > THIRTY_DAYS:
            await session_service.delete_session(
                app_name=app_name, user_id=user_id, session_id=listed.id
            )
            removed += 1
    return removed
```

Two cautions: deletion is permanent — with `InMemorySessionService` it is also immediate and unrecoverable, so archive-before-delete belongs in *your* code. And run purge jobs against a persistent service on a schedule, not inside the request path, where a slow `list_sessions` would sit in front of users.

## Checklist

- [ ] Every conversation starts with `create_session` (or `Runner(auto_create_session=True)`).
- [ ] No code writes to a `Session` fetched from the service — commits go through `append_event` / the `Runner`.
- [ ] `list_sessions` results are treated as metadata-only; detail reads use `get_session`.
- [ ] Heavy reads use `GetSessionConfig(num_recent_events=...)` instead of full history.
- [ ] `SessionNotFoundError` is handled (or avoided) with a create-fallback, and it is a `ValueError`.
- [ ] A retention policy uses `last_update_time` to decide what to archive or purge.
- [ ] Deletion runs as an explicit, scheduled step — never as a side effect of a request.
- [ ] The production `SessionService` is persistent, so "restart" does not mean "amnesia".

## Conclusion

The ADK session lifecycle is deliberately small: create or resume, let the `Runner` append events for each turn, list when you need an overview, delete when the data has served its purpose. Everything painful about session management — the not-found errors, the empty list results, the unbounded growth — comes from skipping one of those beats. Treat `create_session` as your entry ticket, `append_event` as the only write path, and `delete_session` as a scheduled policy rather than an afterthought, and conversations behave like the durable records they are meant to be.

## References

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