AI Hints
Home›LangGraph Tutorial›Reliability
LangGraph · Lesson 81 of 120

Node Caching

Skip repeated work.

⏱ 2 min read▶ Video at 1:27:02🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

Some nodes do slow work, and get the same input again and again. Like summarising the same book description, for every customer who asks. Node caching remembers a node's result for a given input, and skips the work next time.

Node Caching
From the video: Node Caching
  • Slow nodes
  • Same input again
  • Remember the result

A cached node

The describe node sleeps for one second, to stand in for slow work. We add it with a cache policy, keeping results for sixty seconds, and compile with an in memory cache. Then we invoke twice with the same input. Run it. The first run takes about a second. The second returns instantly, from the cache.

node_cache.pypython
import time
from typing import TypedDict
from langgraph.cache.memory import InMemoryCache
from langgraph.graph import StateGraph, START
from langgraph.types import CachePolicy

class State(TypedDict):
    title: str
    blurb: str

def describe(s):
    time.sleep(1)                       # slow work, like a model call
    return {"blurb": f"{s['title']}: an epic of sand and politics."}
b = StateGraph(State)
b.add_node("describe", describe, cache_policy=CachePolicy(ttl=60))
b.add_edge(START, "describe"); graph = b.compile(cache=InMemoryCache())
for run in [1, 2]:
    start = time.perf_counter(); graph.invoke({"title": "Dune"})
    print(f"run {run}: {time.perf_counter() - start:.2f}s")
Output
run 1: 1.01s
run 2: 0.00s

Caching tips

The cache key is the node's input, so only identical inputs hit the cache. Ttl is how long results stay, in seconds. Cache nodes whose results don't change often. And never cache nodes with side effects, like placing an order.

keyvalue
Keythe node's input
ttlseconds to keep
Good forslow, repeatable work
Neverside effects

Summary

A cache policy on a node, plus a cache at compile, skips repeated work for identical inputs. Next, passing per run settings with runtime context.

Key takeaways
  • CachePolicy(ttl=...)
  • compile(cache=...)
  • Same input, instant
Next up: Runtime Context — per-run settings