---
title: "Serializing Complex Custom Objects into Session State"
date: "2026-12-03T08:32:05+07:00"
description: "State values must be serializable — so how do you track a dataclass, a datetime, or a database record? Convert to plain data, keep identifiers, and hand binary payloads to artifacts."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-serializing-custom-objects-state.jpg"
alt: "A complex custom object being flattened into a simple key-value pair for storage"
tags: ['google-adk', 'state-management', 'serialization', 'pydantic', 'artifacts']
---

The error rarely appears where you expect it. You store a perfectly reasonable `BookingRecord` in `session.state`, the agent runs fine for a few turns, and then a restart or a `DatabaseSessionService` write silently loses the field — or worse, the whole update. ADK's rule is blunt: **state values must be serializable**, because the `SessionService` has to save and reload them through storage that speaks JSON, not Python.

That rule does not mean you cannot track rich domain objects. It means you need a conversion discipline: flatten what belongs in state, keep an identifier for what does not, and hand genuinely large or binary payloads to artifacts. This tutorial gives you the mapping table and the code for each case — including the `StateSchemaError` edge cases that catch even careful authors.

## Prerequisites

- ADK installed and a `Runner` with a `SessionService` you have used.
- Familiarity with `output_key` and `EventActions(state_delta)` for writing state.
- Optional: Pydantic models in your codebase (ADK itself uses Pydantic for `state_schema` validation).

## 1. What is legal in state

State is a dictionary of `key: value` pairs with two constraints:

- **Keys:** always strings (`str`).
- **Values:** must be **serializable** — strings, numbers, booleans, and simple lists or dictionaries containing *only* those basic types.

The docs' warning is explicit: *do not store non-serializable objects (custom class instances, functions, connections, etc.) directly in the state. Store simple identifiers if needed, and retrieve the complex object elsewhere.* The moment your value is something the storage backend cannot round-trip, you have a latent data-loss bug.

## 2. The conversion table

Every common Python type has a correct home:

| Type | Why it fails in state | What to store instead |
| --- | --- | --- |
| `datetime` / `date` | Not JSON-native; `State` may drop it | ISO-8601 string or epoch number |
| `UUID` | Custom object | `str(uuid)` |
| `Enum` | Custom object | `.value` (string/int) |
| Dataclass | Custom class instance | `dataclasses.asdict()` / `dataclasses.astuple()` |
| Pydantic model | Custom class instance | `model.model_dump()` |
| SQLAlchemy / ORM row | Connection-backed object | Primary key + reconstruct with a query |
| `bytes` / file content | Binary, bloats the row | Artifact (`GcsArtifactService`) + filename in state |
| Function / lambda | Not serializable at all | Register by name; look up in a registry |
| DB connection / client | Live resource | Identifier or config; construct elsewhere |

Two patterns cover 95% of cases: **flatten** (convert the object to plain data before writing) and **reference** (store an ID, rebuild on read).

## 3. Flattening rich objects

Convert at the boundary — right before the value enters `state_delta`:

```python
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from enum import Enum
from uuid import uuid4

class BookingStep(Enum):
    PICK_DATE = "pick_date"
    CONFIRM = "confirm"

@dataclass
class BookingRecord:
    destination: str
    step: BookingStep
    created_at: datetime
    ref_id: str

record = BookingRecord(
    destination="Tokyo",
    step=BookingStep.PICK_DATE,
    created_at=datetime.now(timezone.utc),
    ref_id=str(uuid4()),
)

# Flatten to only serializable primitives.
flat = {
    "booking_destination": record.destination,          # str
    "booking_step": record.step.value,                  # str via Enum.value
    "booking_created_at": record.created_at.isoformat(),# str via isoformat()
    "booking_ref": record.ref_id,                       # str via uuid4()
}
# Or, if you prefer one key:
# flat = {"booking": asdict(record) | {"step": record.step.value}}
```

With a Pydantic model, `model_dump()` does the same job:

```python
from pydantic import BaseModel

class UserProfile(BaseModel):
    name: str
    locale: str
    signup_at: datetime

profile = UserProfile(name="Ari", locale="th-TH", signup_at=datetime.now(timezone.utc))

# datetime is not JSON-safe by default — use a JSON-compatible dump mode.
flat_profile = profile.model_dump(mode="json")   # datetime -> str
```

`model_dump(mode="json")` is the detail people miss: plain `model_dump()` still leaves `datetime` objects inside the dict, which is exactly the non-serializable payload you were trying to avoid.

## 4. The reference pattern

Some objects cannot be flattened — they are rows in a database, rows in a cache, entries in a vector store. Store the **identifier** and reconstruct on read:

```python
# WRITE: only the key, never the ORM object.
changes = {"cart_id": str(cart.id), "cart_updated_at": cart.updated_at.isoformat()}
event = Event(invocation_id=..., author="system",
              actions=EventActions(state_delta=changes))
await session_service.append_event(session, event)

# READ: rebuild the object where you need it.
cart = await cart_repository.load(session.state["cart_id"])
```

The same pattern applies to functions: keep a registry keyed by name, store the name, and resolve it when the invocation runs.

## 5. Binary and large payloads: artifacts

State is text-shaped. When the payload is a PDF, an image, or a generated report, use **artifacts** — binary blobs managed by an `ArtifactService` with only a reference kept in state:

```python
import google.genai.types as types
from google.adk.artifacts import GcsArtifactService

artifact_service = GcsArtifactService(bucket="my-agent-bucket")

runner = Runner(
    agent=agent,
    app_name="report_app",
    session_service=session_service,
    artifact_service=artifact_service,
)

# Inside a tool or callback:
report_part = types.Part.from_bytes(data=report_bytes, mime_type="application/pdf")
version = await context.save_artifact(filename="generated_report.pdf",
                                       artifact=report_part)
# Keep only the reference in state:
#   {"report_file": "generated_report.pdf", "report_version": version}
```

The `Runner` confirms the write through the event's `artifact_delta`, exactly as it confirms state changes through `state_delta`. Note that if no `artifact_service` is configured on the `Runner`, `save_artifact` raises a `ValueError` — wire the service first.

## 6. Validation: `StateSchemaError` and its blind spots

ADK can validate state shape via a Pydantic `state_schema`, which raises `StateSchemaError` (`google.adk.sessions.state`) on bad writes. Understand exactly where it checks — and where it does not:

| Situation | Validated? | Consequence |
| --- | --- | --- |
| `state[key] = value` (top-level) | Yes | Bad types raise `StateSchemaError` |
| `state.update({...})` (top-level) | Yes | Same as above |
| Key contains `:` (e.g. `user:x`) | **No** | Prefixed keys bypass validation |
| Nested write: `state[key]["sub"] = v` | **No** | Reaches the delta unvalidated |
| Container whose JSON form differs (protobuf, `datetime`) | **No** | `State` keeps current value + pending delta and *drops* containers that don't match |

The `State` object holds both the current value and the pending delta; when a container's JSON serialization differs between the two (protobuf messages, datetimes), the update can be dropped rather than stored. This is why `datetime` is on the "flatten first" list even though it *looks* harmless — validation will not save you, and the drop is silent.

Practical rules:

1. Validate at the boundary yourself — convert before writing, not after.
2. Treat prefixed keys (`user:`, `app:`, `temp:`) as unvalidated: extra care on their value types.
3. Assign whole top-level keys rather than mutating nested containers in place when you can — top-level assignment is the path that *is* checked.
4. Never write to a `Session` fetched from the `SessionService` directly; mutate the `Context`'s `state` or emit a `state_delta`. Direct mutation bypasses tracking entirely.

## Checklist

- [ ] Every state value is a string, number, boolean, or a simple list/dict of those.
- [ ] `datetime` values are converted (`.isoformat()` or epoch) before entering `state_delta`.
- [ ] Enums are stored as `.value`, UUIDs as `str(...)`.
- [ ] Pydantic models use `model_dump(mode="json")`, not bare `model_dump()`.
- [ ] Dataclasses use `asdict()` (or manual field extraction) at the write boundary.
- [ ] ORM rows and other un-flattenable objects are stored as identifiers and reconstructed on read.
- [ ] Binary/large payloads live in an `ArtifactService` (`GcsArtifactService`) with only a filename/version reference in state.
- [ ] `artifact_service` is passed to the `Runner` before any `save_artifact` call.
- [ ] Top-level writes are preferred over nested mutation (only top-level assignment is schema-validated).
- [ ] No fetched `Session` object is ever mutated directly.

## Conclusion

Serialization is not an obstacle to rich state — it is the contract that lets the `SessionService` persist, replay, and thread-safely update your agent's memory. Flatten objects to primitives, reference what you cannot flatten, and delegate binary payloads to artifacts with a pointer in state. Add a hard look at `StateSchemaError`'s blind spots — prefixed keys, nested writes, JSON-mismatched containers — and your complex domain data will survive every restart, every redeploy, and every event replay.

## References

- https://adk.dev/sessions/state/
- https://adk.dev/artifacts/
- https://adk.dev/sessions/session/
