LangGraph node caching: include input revisions in the key
Set key_func and TTL for a deterministic text node, then inspect repeated input, revision changes and expiration.
List the actual dependencies · Attach both the cache and node policy · Inspect reuse and invalidation paths
At a glance
LangGraph can cache node results by input. A key that omits a dependency may reuse an incorrect result. This task designs acceptance around synthetic whitespace normalization: the key includes text, source revision and rule revision; the node has a teaching TTL of 30 seconds; compilation receives an in-memory cache. The deliverable is a cache definition and hit/invalidation record. The work is deliberately small and proves no speedup. LangGraph and models were not run.
Runtime and applicability
- Article type
- Engineering practice
- Verified
- Applies to
- LangGraph Python node caching and input revision checks
Execution locations and responsibilities
- Python graph definition and caller process Define inputs, key_func and TTL, bind a cache and retain path checks.
When to use
- A node receives repeated inputs and its result may be reused, with all dependencies and an acceptable lifetime identified.
When not to use
- Caching is not a Checkpointer or Store. Reusing a result neither resumes thread progress nor guarantees an external write happens once.
- If permissions, external data or model configuration affect a result but are absent from its key, account for them before claiming correctness. A shorter TTL alone is insufficient.
List the actual dependencies
The execution locations are the Python graph definition and its calling process. An installation compatible with the documented APIs is required. Synthetic input has text and source_revision; output has result. The rule revision is normalize-v1. These version strings are application choices, not versions generated by LangGraph. A model node may also depend on model name, prompt, tenant or retrieval results; decide how each enters the key.
Attach both the cache and node policy
The documentation requires a cache at graph compilation and CachePolicy on the node. key_func creates a key from node input; the default hashes input through pickle. ttl is in seconds, and omitted TTL means no expiration. The JSON key avoids ambiguity from simple string concatenation. Thirty seconds is a teaching lifetime. The in-memory example establishes neither persistence across restarts nor cross-process sharing.
import json
from typing_extensions import TypedDict
from langgraph.cache.memory import InMemoryCache
from langgraph.graph import END, START, StateGraph
from langgraph.types import CachePolicy
class State(TypedDict):
text: str
source_revision: str
result: str
def cache_key(state: State) -> str:
return json.dumps(
[state["text"], state["source_revision"], "normalize-v1"],
ensure_ascii=False,
separators=(",", ":"),
)
def normalize(state: State) -> dict[str, str]:
print("normalize node executed")
return {"result": " ".join(state["text"].split())}
builder = StateGraph(State)
builder.add_node(
"normalize", normalize,
cache_policy=CachePolicy(key_func=cache_key, ttl=30),
)
builder.add_edge(START, "normalize")
builder.add_edge("normalize", END)
graph = builder.compile(cache=InMemoryCache())
first = {"text": "Release notes", "source_revision": "demo-1"}
revised = {"text": "Release notes", "source_revision": "demo-2"}
print(graph.invoke(first, stream_mode="updates"))
print(graph.invoke(first, stream_mode="updates"))
print(graph.invoke(revised, stream_mode="updates"))
Inspect reuse and invalidation paths
| Path | Key and policy | Expected check |
|---|---|---|
| First demo-1 | New key | Execute and return result |
| Immediate repeat of demo-1 | Same unexpired key | Cache can return; inspect cached metadata |
| Change to demo-2 | Source revision changes the key | Reexecute even when text is identical |
| After teaching TTL, use demo-1 | Original entry expired | Reexecute; record actual timing |
The script’s three calls cover the first three rows. For expiration, wait beyond TTL and invoke first again in the same process, so restart loss does not masquerade as expiration. None of these paths was run here and no observed output is shown. The official updates-mode example includes __metadata__: {cached: true} on a cached result. Compare that metadata with execution prints, not just equal result strings.
Equal results do not validate the key
demo-1 and demo-2 have the same text, so both should normalize to Release notes. That equality comes from the content and cannot prove cache reuse. A changed revision needs a distinct key; inspect reexecution to check it. Removing source_revision can still yield the same text without passing revision invalidation. TTL controls time, not omitted dependencies.
Separate failures, recovery and cleanup
- Stop on import or policy incompatibility and inspect installed dependencies. Removing caching is not a passing cache check.
- On an unexpected miss, inspect graph/cache instance reuse, expiration and actual node input.
- If a revised input incorrectly reuses prior work, stop consumption and fix the key before rechecking.
- On process closure or cancellation, stop new calls and keep existing records. An in-memory cache is not persistence evidence.
- Paid calls or external writes need separate failure, idempotency and permission policies. Caching does not guarantee side-effect deduplication.
Deliver a reproducible configuration record
Record graph/cache scope, node name, dependencies, key-rule revision, TTL, actual results for all four paths and unexecuted work. Acceptance requires first execution, repeat reuse, dependency invalidation and expiration to match the design. Parseable code or output verifies only that layer, not cache behavior, performance or facts. Python SqliteCache is also documented but is not configured here.
Verification scope
The current Python node-caching section and graph compilation guidance were read. This original example did not run LangGraph, install dependencies, wait for expiration or call models. It is not a production performance measurement and does not implement Checkpointer, Store or durable recovery.
Sources
All links are official pages; verification dates are listed per source, and links point to the version checked.