Production, edge, audit and resilience
Technical series · Article 3 of 3
Two articles to get to the graph. This is to bring it into production without it collapsing during the first real exercise.
The tactical C2 has constraints that a notebook PoC ignores:
- Intermittent mesh (edge, tactical mesh)
- Sub-second latency for some decisions
- Immutable audit trail for post-mission review
- Operators working in shifts — the workflow must survive the changing of guards
- LLM models that may be slow, expensive or temporarily unavailable
Deployment architecture
flowchart TB
subgraph EDGE["Nodo tattico edge"]
ING[Ingest locale Kafka]
CACHE[Redis — stato caldo]
LG[LangGraph runtime]
LLM_LOCAL[LLM on-device / quantizzato]
RULE[Rule engine ROE]
end
subgraph CORE["Core operations — quando connesso"]
PG[(PostgreSQL checkpointer)]
API[Mission API]
CON[Console operatore]
LS[LangSmith / OTel]
end
subgraph RESIL["Resilienza"]
CB[Circuit breaker LLM]
FB[Fallback deterministico]
Q[Dead letter queue]
end
ING --> LG
LG --> CACHE
LG --> LLM_LOCAL
LG --> RULE
LG <-->|sync quando link up| PG
LG --> API
API --> CON
LG --> LS
LLM_LOCAL --> CB
CB -->|open| FB
LG --> QPrinciple: the graph runs on the tactical node. The cloud (if there is one) is for persistence, observability and training — not for the critical decision loop.
Checkpointer: PostgreSQL vs SQLite vs Redis
| Backends | When to use it | Trade-offs |
|---|---|---|
MemorySaver | Tests, dev | Zero persistence |
SqliteSaver | Single Edge, air-gapped | Lightweight, one knot |
PostgresSaver | Multi-operator TOC | ACID, query audit |
| Custom Redis | Hot state + TTL | Fast, need backup |
In production I use double layer:
# Stato caldo — accesso rapido per UI
redis_store = RedisSaver(redis_client, ttl=86400)
# Stato freddo — audit e post-mission
postgres_store = PostgresSaver.from_conn_string(DB_URI)
def hybrid_checkpointer(config):
thread_id = config["configurable"]["thread_id"]
hot = redis_store.get(config)
if hot:
return hot
return postgres_store.get(config)The thread_id becomes the key to everything: mission, operator, shift.
LLM resilience: circuit breaker and fallback
An LLM that spends 30 seconds on a CRITICAL event is an LLM that does not exist.
from tenacity import retry, stop_after_attempt, wait_exponential
from circuitbreaker import circuit
@circuit(failure_threshold=3, recovery_timeout=60)
@retry(stop=stop_after_attempt(2), wait=wait_exponential(min=1, max=8))
def invoke_threat_model(messages: list) -> ThreatAssessment:
return chat_model.with_structured_output(ThreatAssessment).invoke(messages)
def threat_assessment_node(state: C2State) -> dict:
try:
assessment = invoke_threat_model(state["messages"])
except Exception as e:
# Fallback deterministico — mai bloccare il ciclo
assessment = rule_based_threat_fallback(state["tracks"])
assessment.uncertainty_factors.append(f"LLM unavailable: {type(e).__name__}")
return {
"threat_level": assessment.threat_level,
"audit_trail": [{
"node": "threat_assessment",
"source": "llm" if "LLM unavailable" not in str(assessment.uncertainty_factors) else "fallback",
"output": assessment.model_dump(),
}],
}Operational rule: the graph never stops due to an LLM error. Degrade with transparency — the operator sees source: fallback in the console.
Timeout and automatic escalation
import asyncio
from datetime import datetime, timedelta
APPROVAL_TIMEOUT_MINUTES = 15
async def approval_timeout_watcher(thread_id: str):
config = {"configurable": {"thread_id": thread_id}}
deadline = datetime.utcnow() + timedelta(minutes=APPROVAL_TIMEOUT_MINUTES)
while datetime.utcnow() < deadline:
snapshot = app.get_state(config)
if snapshot.next != ("human_gate",):
return # già risolto
await asyncio.sleep(30)
# Timeout scattato
app.update_state(config, {"human_approval": "TIMEOUT"})
app.invoke(None, config) # entra nel branch escalationThe escalate branch can:
- Notify the next shift commander
- Raise the alert level without carrying out offensive actions
- Record a governance event for post-mission review
Audit trail: beyond LangSmith
LangSmith tracks LLM calls. In C2 you also need decision audit — independent of the vendor:
def append_audit(state: C2State, entry: dict) -> list[dict]:
entry["timestamp"] = utcnow().isoformat()
entry["thread_id"] = get_current_thread_id()
entry["checksum"] = sha256(json.dumps(entry, sort_keys=True)).hexdigest()[:16]
return state["audit_trail"] + [entry]Post-mission export:
def export_mission_audit(thread_id: str) -> MissionReport:
config = {"configurable": {"thread_id": thread_id}}
history = list(app.get_state_history(config))
return MissionReport(
thread_id=thread_id,
checkpoints=len(history),
audit_trail=flatten_audit(history),
human_decisions=extract_human_gates(history),
llm_vs_fallback_ratio=compute_source_ratio(history),
)get_state_history() is one of LangGraph's most underrated features: rebuild entire mission checkpoint by checkpoint.
Observability: Metrics that matter
"The graph is finished" is not enough. I monitor:
# Prometheus metrics esempio
GRAPH_NODE_DURATION = Histogram(
"c2_graph_node_duration_seconds",
"Durata esecuzione nodo",
["node_name", "threat_level"],
)
HUMAN_GATE_WAIT = Histogram(
"c2_human_gate_wait_seconds",
"Tempo attesa approvazione operatore",
)
LLM_FALLBACK_TOTAL = Counter(
"c2_llm_fallback_total",
"Volte usato fallback deterministico",
["node_name"],
)Operational dashboard — what I look at every morning:
| Metric | Alert threshold | Meaning |
|---|---|---|
human_gate_wait p95 | > 10 min | Saturated operators or slow UI |
llm_fallback_total installments | > 5% / hour | Degraded model or network |
graph_node_duration{classify} p99 | > 2s | Ingest or slow fusion |
| Checkpoint gap | > 1h on active mission | Abandoned Workflow |
Deploy with LangGraph Platform / self-hosted
Two ways I used:
Self-hosted (full control, edge)
# docker-compose.yml — estratto
services:
c2-graph:
image: c2-langgraph:latest
environment:
- CHECKPOINTER_URL=postgresql://...
- REDIS_URL=redis://...
- LLM_ENDPOINT=http://llm-local:8080
volumes:
- ./graphs:/app/graphs
deploy:
resources:
limits:
memory: 4GThe graph is a stateless service — the state lives in the checkpointer. You can restart the container without losing ongoing missions.
LangGraph Platform (iteration speed)
Useful in the development phase and for distributed teams: graph deployment with managed API, studio for visual debugging, cron for recurring workflows.
In edge tactical production, I stay at self-hosted with local Postgres.
Security: what to worry about
- `thread_id` unguessable — UUID v4, non-sequential
- RBAC on Mission API — only authorized operators call
approve - Prompt injection from feeds — sanitizing sensor inputs before they enter
messages - Secrets out of graph — LLM API key in vault, not state
- Audit immutability — append-only, never passed
updatetoaudit_trail
def sanitize_track_feed(raw: dict) -> Track:
"""I feed esterni non devono mai finire verbatim nel prompt LLM."""
return Track(
track_id=validate_uuid(raw.get("track_id")),
source=allowlist_source(raw.get("source")),
position=clamp_coordinates(raw.get("position")),
confidence=min(max(float(raw.get("confidence", 0)), 0), 1),
timestamp=parse_iso_timestamp(raw.get("timestamp")),
)Performance: where to really optimize
| Bottleneck | Solution |
|---|---|
| Slow LLM | Quantized on-device model, structured output, short prompt |
| Checkpointer I/O | Redis hot + Postgres async flush |
| Graph too large | Subgraph, lazy activation on significant events |
| Too many checkpoints | checkpoint_during=False on idempotent nodes |
| Sensor Fusion | Outside the graph — stream processing, trigger-only graph |
The LangGraph does not have to process every radar packet. Must orchestrate decisions.
Post-mission review: the hidden value
After an exercise, the team asks, “Why did we propose INTERCEPT instead of MONITOR?”
With get_state_history() I reply in 10 minutes:
for snapshot in app.get_state_history(config):
audit = snapshot.values.get("audit_trail", [])
for entry in audit:
if entry["node"] == "threat_assessment":
print(f"@{entry['timestamp']}: {entry['output']}")
if entry["node"] == "operator_console":
print(f"Operator {entry['operator_id']}: {entry['decision']}")This is the real ROI: not automation for automation, but transparent, repeatable, improvable decision cycle.
Production checklist
- [ ] State typed with tested reducers
- [ ] Persistent checkpointer (not MemorySaver)
- [ ]
interrupt_beforeon all human gates - [ ] Deterministic fallback for each LLM node
- [ ] Timeout and escalation on the human gate
- [ ] Append-only audit trail with post-mission export
- [ ] Prometheus metrics + trace LangSmith/OTel
- [ ] Test the graph as a state machine (not just unit tests on nodes)
- [ ] Sanitization of inputs from external feeds
- [ ] Stateful stateless deployment in checkpointer
🔥 Closing of the series
LangGraph for Tactical C2 is not a hackathon experiment. It is an orchestration engine that allows you to model:
- Decisions with explicit state
- Specialized agents coordinated, not a single oracle
- Human-in-the-loop native, not hooked
- Persistence and recovery for long-running missions
- Audit for compliance and post-mission review
The difference between a demo and an operating system is here: architectural governance, resilience, and the knowledge that the LLM is a component — not the command.
If you are designing complex application workflows — in defense, critical industry, or any domain with high-impact decisions — the graph is not over-engineered. It's the right model.
