NATS State Store

@purista/nats-state-store uses NATS JetStream Key-Value as the state backend. If your services already communicate over NATS, this keeps your infrastructure footprint small — one technology covers messaging, config, and state.

JetStream required. NATS must be started with JetStream enabled (nats-server -js).

Capabilities

FeatureSupport
Read (getState)
Write (setState)✅ (opt-in)
Delete (removeState)✅ (opt-in)
Persistence across restarts✅ (JetStream)
Watch / reactive updates✅ (JetStream KV watchers)
Replication✅ (JetStream clustering)
TTL / entry expiry✅ (JetStream KV TTL)

Install

npm install @purista/nats-state-store

Setup

import { NatsStateStore } from '@purista/nats-state-store'

const stateStore = new NatsStateStore({
  servers: process.env.NATS_URL ?? 'nats://localhost:4222',
  // JetStream KV bucket name (created automatically if it does not exist):
  // bucketName: 'purista-state',
  enableSet: true,
  enableRemove: true,
})

const myService = await myV1Service.getInstance(eventBridge, { stateStore })

All NATS JavaScript client connection options are supported — TLS, credentials files, cluster seed URLs.

Usage inside a handler

.setCommandFunction(async function (context, payload) {
  await context.states.setState('lastProcessedAt', new Date().toISOString())
  const { lastProcessedAt } = await context.states.getState('lastProcessedAt')

  await context.states.removeState('expiredKey')
})

Operational tips

  • Use separate KV buckets per service or environment to avoid key collisions and simplify access control
  • Set replicas: 3 on the JetStream KV bucket for HA in production NATS clusters
  • JetStream KV supports per-key TTL — use it to implement session expiry or cache invalidation without a separate cleanup job
  • NATS JetStream KV watchers enable real-time state change notifications across services — useful for reactive architectures