The Complete Production SOP: How to Deploy and Run NATS JetStream Persistence & Distributed Messaging in Autonomous AI Agents
Step-by-step SOP to install and run NATS JetStream Persistence & Distributed Messaging in Codex, Claude Code, and Cursor with Go code examples and error fixes.
Technical Overview & Architectural Context
Distributed messaging with NATS JetStream requires precise configuration of stream retention policies, consumer acknowledgement semantics, and consumer durability. Autonomous AI agents frequently hallucinate core NATS core publish/subscribe mechanisms instead of JetStream persistent APIs, omit essential acknowledgement calls (like msg.Ack() or msg.NakWithDelay()), or misconfigure stream subject overlaps, leading to unacknowledged message deadlocks and runaway broker storage. The 'nats-jetstream-at-least-once' skill establishes deterministic architectural guardrails for autonomous coding agents (Codex, Claude Code, Cursor, and Windsurf). It enforces file-based persistence setup (`store_dir`), explicit stream creation via `AddStream`, bounded batch pull consumers with timeouts, and deterministic message lifecycle acknowledgments across Go and polyglot microservice environments.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into the agent runtime.
Autonomous coding assistants evaluate local `.agents/skills` or project-scoped `.claude/skills` directories on boot. By downloading the canonical `nats-jetstream-at-least-once` definition into your workspace, the agent runtime monitors YAML trigger phrases like 'create nats jetstream stream' and hot-reloads SOP constraints into its system instruction set without polluting global system tokens.
mkdir -p .agents/skills/nats-jetstream-at-least-once && curl -fsSL https://askills.dev/api/skills/nats-jetstream-at-least-once/raw -o .agents/skills/nats-jetstream-at-least-once/SKILL.md---
name: "nats-jetstream-at-least-once"
description: "Implement lightweight, high-speed publish-subscribe and persistent streams with NATS JetStream."
metadata:
author: "NATS"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "create nats jetstream stream"
- "consume nats jetstream messages"
- "setup nats kv bucket"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# NATS JetStream Persistence & Distributed Messaging
Builds messaging architectures with NATS JetStream: creating file/memory streams, defining consumer subjects, configuring at-least-once / exactly-once acknowledgments, key-value (KV) buckets, and object stores.
## Execution SOP & Rules
1. Enable JetStream in nats-server configuration: jetstream: { store_dir: '/data/jetstream' }.
2. Create stream: js.AddStream(&nats.StreamConfig{ Name: 'ORDERS', Subjects: []string{'orders.*'}, Storage: nats.FileStorage }).
3. Create pull consumer and fetch batches: msgs, _ := sub.Fetch(10, nats.MaxWait(time.Second)).
4. Acknowledge message processing: msg.Ack() or call msg.NakWithDelay() on transient failures.Mount skills in workspace-level `.agents/skills` rather than global directories to prevent context cross-contamination across non-NATS microservices.
Ensure your agent sandbox permissions allow reading markdown definitions in `.agents/skills` or `.claude/skills`; restricted root sandboxes will fail to register the trigger match.
Environment Secrets & NATS Broker Configuration
Configure broker connection strings and persistence directories without committing credentials to source control.
Provide the runtime environment with connection parameters to the NATS broker. Ensure `NATS_URL` and security credentials (NKeys or TLS client certs) are supplied via environment variables or `.env.local` files rather than hardcoded in Go source code generated by the agent.
printf "NATS_URL=nats://127.0.0.1:4222\nNATS_JETSTREAM_DIR=./tmp/jetstream\n" > .env.local && echo ".env.local" >> .gitignoreUse `nats-server -js -sd ./tmp/jetstream` during local development to run an embedded JetStream-enabled daemon quickly without Docker dependencies.
Never expose `.env.local` with NKey private seeds in agent conversation context, as it risks accidental inclusion in git history.
Intent Matching & Trigger Invocation
Verify deterministic activation using tested natural language prompts matching SKILL.md triggers.
Send a prompt matching one of the frontmatter trigger strings (e.g., 'create nats jetstream stream' or 'consume nats jetstream messages'). The runtime engine scans AST tokens, pairs the intent with the registered skill, and compels the agent to implement persistent JetStream patterns rather than ephemeral core NATS pub/sub.
Explicitly reference the trigger phrasing in task directives (e.g., 'Execute SOP: create nats jetstream stream for order processing') to guarantee 100% trigger accuracy.
Verification, Linting & Output Quality Gate
Execute automated self-healing checks and run integration tests against the JetStream broker.
Instruct the autonomous agent to invoke the Go test harness against an active JetStream server instance to verify at-least-once message delivery, stream configuration durability, and proper consumer acknowledgement before committing changes.
go vet ./... && go test -v -race -run TestJetStreamOrderStream ./...Check `nats stream info ORDERS` via CLI during agent test execution to ensure uncommitted messages do not exceed expected consumer batch sizes.
Real-World Scenario: Provision Durable Orders Stream and Resilient Batch Pull Consumer in Go
“We need to handle incoming transactions reliably. Please create nats jetstream stream named 'ORDERS' with subject 'orders.*' using file persistence, then implement a durable pull consumer worker in Go that fetches batches of 10 messages, acknowledges successful processing with msg.Ack(), and backs off with msg.NakWithDelay(5 * time.Second) on processing errors.”
Runtime Troubleshooting & Failure Modes
Root Cause: The target NATS broker daemon was started in core pub/sub mode without the -js or --jetstream flag, preventing stream management APIs from executing.
nats-server -js -sd /tmp/nats-data or configure `jetstream { store_dir: "/data/jetstream" }` in /etc/nats/nats-server.confRoot Cause: Attempted to call `js.AddStream` with modified subjects or storage types on an existing stream without performing `js.UpdateStream` or migrating configuration.
nats stream edit ORDERS --subjects "orders.*,orders.refunds" or check existence before creation using `_, err := js.StreamInfo("ORDERS")`Frequently Asked Questions (NATS JetStream Persistence & Distributed Messaging SOP)
Q:Can I use NATS JetStream Persistence & Distributed Messaging across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification supported across all modern agent runtimes by mounting the specification in your workspace configuration directory.
Q:How does NATS JetStream Persistence & Distributed Messaging prevent context window overflow during long agent sessions?
By establishing concise procedural boundaries and deterministic validation gates rather than polluting system prompts with redundant rules, keeping agent token footprints minimal.
Q:Does this skill require escalated root or container permissions?
No. It is audited with a security score of 98/100 and runs safely within workspace-scoped sandboxes without demanding shell escalation or arbitrary network sockets outside broker interaction.
Ready to equip your autonomous agent with NATS JetStream Persistence & Distributed Messaging?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.