Cookbook: Stateful agent
Agent that maintains data across invocations: counters, cursor positions,
draft artifacts, memoised lookups. All via ctx.state — per-instance,
tenant-scoped, durable across container restarts.
Reads/writes: ctx.state.get/set/delete/list.
Lifetime: survives invocations, container restarts, agent upgrades.
Does not survive manual portal "clear state" ops or tenant deletion.
Three canonical patterns#
Pattern 1: Counter + atomic increment#
# Simple counter — read-modify-write
count = (await ctx.state.get("processed_count")) or 0
await ctx.state.set("processed_count", count + 1)
Not atomic across concurrent invocations. For a counter that needs atomicity (rare — Konstera invocations rarely overlap on the same instance), use a dedicated counter table via a connector:
# Guaranteed atomic — via Postgres connector
await ctx.connector.call(
"pg_metrics", "query",
{"sql": "UPDATE agent_counters SET n = n + 1 WHERE agent_id = $1 RETURNING n",
"params": [ctx.instance_id]},
)
Pattern 2: Cursor advancement#
Scheduled agents polling for new work. Pattern: load cursor → fetch since-cursor → process → advance cursor after success.
from datetime import datetime, timezone
class PollingAgent(Agent):
async def handle(self, req, ctx):
# Load cursor; first run defaults to "process starting now"
cursor_str = await ctx.state.get("last_processed_at")
cursor = (
datetime.fromisoformat(cursor_str)
if cursor_str
else datetime.now(timezone.utc)
)
# Fetch since cursor
new_items = await ctx.capability.call(
"tickets.list_unresolved",
since_iso=cursor.isoformat(),
limit=100,
)
if not new_items:
return AgentResponse(content="", structured={"processed": 0})
# Process each
processed = 0
for item in new_items:
try:
await self._process_one(item, ctx)
processed += 1
except Exception as e:
await ctx.log.warn("process.failed", item_id=item.get("id"), error=str(e))
# Don't advance cursor past a failure — next run will retry
# Advance cursor AFTER successful processing
new_cursor = datetime.now(timezone.utc)
await ctx.state.set("last_processed_at", new_cursor.isoformat())
return AgentResponse(
content=f"Processed {processed} items.",
structured={"processed": processed, "cursor": new_cursor.isoformat()},
)
Advance after, not before. If the agent crashes mid-batch, the retry picks up from the same cursor and re-processes — plus whatever idempotency mechanism the capability provides.
Pattern 3: Cache with TTL-based eviction#
ctx.state has no built-in TTL. Store expiry alongside the value and
check on read:
import time
async def get_cached_customer(ctx, email: str, ttl_seconds: int = 600):
"""Return cached customer lookup or re-fetch if stale."""
key = f"cache:customer:{email}"
cached = await ctx.state.get(key)
if cached and cached.get("expires_at", 0) > time.time():
return cached["data"]
# Miss or expired — re-fetch
customer = await ctx.capability.call("customers.lookup_by_email", email=email)
if customer:
await ctx.state.set(
key,
{"data": customer, "expires_at": time.time() + ttl_seconds},
)
return customer
Periodic cleanup via ctx.state.list(prefix="cache:") + delete expired.
manifest.json#
Stateful agents don't need any special manifest. Just the normal shape:
{
"id": "io.konstera.stateful-example",
"version": "0.1.0",
"runtime": { "kind": "container", "image": "...", "port": 8080 },
"autonomy": "autonomous",
"input": { "type": "object" }
}
What ctx.state is NOT#
- Not shared across instances — each agent instance has its own state
namespace. If you need shared state across instances, use
ctx.vectorwith ashared:<name>namespace or an external DB via a connector. - Not transactional with other operations — a
set()is a single kernel activity; it doesn't participate in multi-step transactions. - Not infinite — tenant quotas apply. Default is 10 MB total per instance; raise via portal if you have a legit case.
Pitfalls#
- Serialisation: values must be JSON-serialisable.
datetime/Decimalfall back tostr()on write — explicit conversion on read. - Key collisions: use prefixes (
cursor:,cache:customer:,profile:) so yourlist()queries are efficient. - Overwriting on race: concurrent handlers can both read the same value, both increment, both write — one loses. If you can't avoid concurrency, move to a connector-backed counter.
- Mega-objects: a single
set("backlog", [100k_items])writes a giant JSON blob. Prefer many keys with a prefix instead.
Common extensions#
- Namespaced state: pattern each agent instance as its own "sub-tenant"
with
ctx.state.set(f"inst:{ctx.instance_id}:...")if the state is really per-instance within a larger coordination. - Soft-delete tombstones: instead of
delete(), mark{"deleted": true}so a periodic cleanup can audit what was removed. - State sync to external store: on
shutdown(), flush recent state changes to an external connector-backed DB for backup. Only works if the shutdown handler completes beforeSIGKILL.
See also#
- Kernel MCP services — state — full API
- Scheduled cron recipe — the main consumer of state
- Agent lifecycle — when state persists vs. reloads