Memory Footprint Optimization in Complex Large-Scale Workflow Graphs
How to keep per-invocation memory low in ADK graph workflows: pass data along edges instead of state, offload big payloads to artifacts, prune temp keys, and compact a growing event history.
Published on • December 2, 2026
AI Assistant

A twenty-node workflow is not slow because it has twenty nodes. It is slow because somewhere around node eight, someone stashed a 4 MB API response in session state, and from that moment on every event carries it, every downstream node deserializes it, and the session record grows without bound. Memory problems in agent graphs are almost never about compute — they are about where you put the data.
ADK’s own documentation is blunt about this: session state “should not be used to persist large amounts of data between nodes.” This article turns that one-line caution into a full data-placement strategy for large-scale graphs — what belongs on an edge, what belongs in state, what belongs in an artifact store, and how to keep the event history from becoming the largest object in your process.
Prerequisites
- ADK Python v2.0.0+ with graph
Workflowexperience (edges,START,Event(output=...)). - A working
SessionService(in-memory is fine for the examples). - Awareness that the
Runnercommits each yielded event’sstate_deltathrough theSessionServicebefore your node resumes — this is why state writes are not free.
1. State is a lightweight key-value store, not a payload bus
The data-handling docs say it twice, in two different places, which is usually a sign that people keep getting it wrong:
Session state is a lightweight key-value store. Do not use it to move large payloads between nodes; use artifacts or a database tool instead.
The reason is structural. State is not a local variable that disappears when a function returns — it is a serializable dictionary that lives in the session, is merged from prefixes, is written into EventActions.state_delta, and is committed by the SessionService on every event that carries a delta. A 4 MB value in state means a 4 MB delta in the event, a 4 MB row in storage, and a 4 MB read the next time any code touches that session.
Treat state as a control plane: flags, IDs, counters, small summaries, decisions. Treat everything bulk-shaped as data-plane traffic that should never enter it.
from google.adk import Event
# Bad: 200 KB of raw API JSON now lives in the session forever.
def fetch_orders(node_input: str):
return Event(state={"orders_raw": big_json_response(node_input)})
# Good: state carries only the handle; the bulk lives elsewhere.
def fetch_orders(node_input: str):
order_ids = big_json_response(node_input)
return Event(state={"order_ids": order_ids, "order_count": len(order_ids)})
2. Pass along the edge when only the next node needs it
The data-handling guide gives a precise decision rule that is worth memorizing:
When only the next node needs a value, pass it along the edge as node
output. Use state when a value must outlive the run, or be read by a tool, a callback, or{key}instruction templating.
Node output is the cheapest channel. It flows from one node to its successor as the typed input parameter — no JSON round trip, no state merge, no persistence:
from google.adk import Event
def analyse_corpus(node_input: str):
"""Heavy intermediate stays on the edge."""
corpus = load_documents(node_input)
chunks = chunk(corpus) # big, but only step 2 needs it
return Event(output=chunks) # handed straight to the next node
def summarise_chunks(chunks: list[str]):
return Event(output=build_summary(chunks))
One hard constraint governs this channel: a node may emit only one Event.output per execution. You can yield as many times as you like for progress messages, but two yields that each carry an output is a runtime error in Python (in other languages each overwrites the last and only the final value reaches the successor). So bundle related values into one serializable object rather than dribbling them out:
def research_step(node_input: str):
yield Event(message="Gathering sources...") # progress, no output
yield Event(output={"sources": srcs, "cost_usd": 0.42}) # the one output
3. Big data goes to artifacts or external storage
When a payload is a document, an image, a dataframe, or a raw API dump, the docs point you at two homes:
- Artifacts — the
ArtifactService(InMemoryArtifactService,GcsArtifactService) stores binary data by reference. Your node saves the artifact and keeps only its identifier in state; theartifact_deltaon the event confirms the write for theRunner. - Database tools — a tool backed by Postgres, Firestore, or object storage that writes and reads rows on demand, so the data is fetched only when a node actually needs it.
The shape of the fix is always the same: store the blob, pass the handle.
from google.adk import Event
async def persist_corpus(node_input: str, ctx: Context):
ref = await ctx.save_artifact(
name="corpus.json",
artifact=build_corpus(node_input),
)
# State holds a few dozen bytes, not several megabytes.
return Event(state={"corpus_ref": ref}, output=ref)
Downstream nodes then load the artifact on demand instead of dragging it through every hop. If a later node genuinely needs the whole payload, it loads it, uses it, and drops the local reference — the value never becomes session-resident.
4. Scope your keys: temp: is your scratch buffer
State keys carry a prefix that decides their lifetime, and choosing the wrong one is a silent memory leak:
| Prefix | Scope |
|---|---|
app: | Shared across all users and sessions for the app |
user: | Tied to the user, shared across their sessions |
temp: | Discarded after the current invocation ends |
| (none) | Persists for the lifetime of the session |
The optimization rules that fall out of this table:
- Scratch data belongs under
temp:. Intermediate calculations, raw responses, and per-invocation caches are discarded when the invocation completes, so they never accumulate across turns. - But
temp:still lives for the whole invocation. A single invocation can span many nodes; atemp:key written at node 2 and never touched again is still resident at node 20. Delete or overwrite it once its consumer has run. - Never write a large value to an unprefixed or
user:key “just for this run” — that value outlives the run, possibly forever, in a persistentSessionService. - Do not park non-serializable objects in state at all. Custom class instances, sockets, and open file handles are explicitly disallowed; store an identifier and reconstruct the object where it is needed.
def score_candidates(node_input: str):
# Written once, read by two nodes, deleted before the node returns.
return Event(state={"temp:candidate_matrix": matrix, "temp:matrix_ready": True})
def cleanup_after_scoring():
return Event(state={"temp:candidate_matrix": None, "temp:matrix_ready": None})
5. Event history growth and context compaction
State is not the only thing that grows. Every event the Runner processes is appended to session.events, and that history is loaded into the model context on later turns. Long-running workflows therefore pay twice: once in resident memory, once in tokens.
ADK’s answer is context compaction, configured through EventsCompactionConfig on an App:
from google.adk.apps.app import App, EventsCompactionConfig
compaction_config = EventsCompactionConfig(
token_threshold=4000, # compact when the prompt exceeds this many tokens
event_retention_size=5, # recent raw events kept un-compacted
)
app = App(
name="my_compacting_agent_app",
root_agent=root_agent,
events_compaction_config=compaction_config,
)
Two strategies are available:
- Token-based (primary) — an absolute safety net sized in real tokens, ideal for unpredictable workloads such as pasted code blocks or uploaded files. It is checked before a model call and again in the
Runnerafter each invocation. - Sliding window (turn-based) — compaction after a fixed number of invocations, useful for predictable chat:
compaction_config = EventsCompactionConfig(
compaction_interval=10, # new invocations between standard compactions
overlap_size=2, # prior invocations retained as overlapping context
)
If you configure both, token-based wins: when the threshold is exceeded it compacts and skips the sliding-window pass for that turn. You can also swap in a cheaper or stronger summarization model with LlmEventSummarizer(llm=Gemini(model="gemini-flash-latest")).
Compaction reduces what the model sees; it does not shrink your application’s working set. It is the token-cost half of the problem, and state discipline is the resident-memory half. You need both.
6. Measuring before you optimize
There is no ADK-specific memory profiler, so instrument the two things you control directly — state size and event count — and use standard Python tooling for the rest:
import sys
import tracemalloc
def report_footprint(ctx: Context, label: str) -> None:
state_bytes = sum(
sys.getsizeof(v) for v in ctx.session.state.values()
)
print(
f"[{label}] keys={len(ctx.session.state)} "
f"state≈{state_bytes // 1024} KB "
f"events={len(ctx.session.events)}"
)
# Around a hot section of the graph:
tracemalloc.start()
run_workflow(...)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"peak={peak // 1024 // 1024} MB")
Three measurements tell you most of what you need:
- State bytes per invocation — if this scales with your input size, you are smuggling payloads through state.
- Peak traced memory across a run — isolates transient churn (large local objects) from retained growth (state and events).
- Event count and average event size — the leading indicator that compaction thresholds are mis-tuned.
Profile with a representative input, not a toy one. Memory bugs in graphs are size-dependent: a workflow that is flat at 10 KB of input can fall off a cliff at 10 MB.
7. A data-placement decision rule
When you are about to write a value anywhere, run it through this:
| Question | Answer → put it in |
|---|---|
| Does only the immediate successor need it? | Event(output=...) on the edge |
| Is it a flag, ID, counter, or small decision? | Session state (unprefixed, or temp: if invocation-scoped) |
Is it needed by a tool, a callback, or a {key} instruction template? | Session state — that is the only channel those read |
| Is it bulk (documents, images, dataframes, raw JSON)? | Artifact or a database tool; pass the reference |
| Is it scratch for this invocation only? | temp: key, deleted when consumed |
| Does it need to survive across sessions for one user? | user: key, or better, memory/artifacts depending on size |
| Is it conversation history? | session.events, with compaction configured |
Checklist
- No node writes bulk data to
state; each passes a reference instead. - Every edge value is a single
outputper node execution — no multi-output yields. - Intermediates that only one successor needs travel on the edge, not in state.
- Large payloads live in artifacts or a database tool, loaded on demand.
- Scratch values use
temp:keys and are cleared when their consumer finishes. - No non-serializable objects are stored in state.
-
EventsCompactionConfigis configured with a realistictoken_thresholdandevent_retention_size. - State bytes, peak memory, and event size are measured on realistic inputs, not demos.
Conclusion
Memory-efficient graphs are not built by micro-optimizing node code; they are built by being disciplined about placement. Edges are for handoffs, state is for control, artifacts are for bulk, temp: is for scratch, and compaction keeps the history from outgrowing the context window. Do that, and a forty-node workflow costs roughly what a five-node one does — because the data never takes a detour through the session.