Skip to main content

NatsPubsub Documentation

Welcome to the comprehensive documentation for NatsPubsub - a production-ready, declarative pub/sub messaging library for NATS JetStream.

What is NatsPubsub?โ€‹

NatsPubsub is a modern, developer-friendly library that brings battle-tested reliability patterns to NATS JetStream. Available in both JavaScript/TypeScript and Ruby, it enables seamless event-driven architecture with guaranteed message delivery, exactly-once processing, and automatic failure handling.

Key Featuresโ€‹

  • ๐ŸŽฏ Declarative API - Intuitive, class-based subscribers inspired by Rails and NestJS
  • ๐Ÿ”’ Reliability Patterns - Built-in Inbox/Outbox patterns and Dead Letter Queue (DLQ)
  • ๐ŸŒ Cross-Language - Full interoperability between Ruby and JavaScript services
  • ๐Ÿงช Testing Support - Comprehensive testing utilities and matchers
  • ๐Ÿ“Š Observability - Built-in metrics, health checks, and monitoring UI
  • โšก High Performance - Optimized for throughput with batching and connection pooling
  • ๐Ÿ›ก๏ธ Type Safety - Full TypeScript support with built-in schema validation
  • ๐Ÿ”ง Auto-Topology - Automatic JetStream stream and consumer management

Quick Navigationโ€‹

Getting Startedโ€‹

Perfect for newcomers to NatsPubsub:

Guidesโ€‹

Step-by-step guides for common tasks:

Patternsโ€‹

Implement reliability patterns:

Integrationsโ€‹

Framework-specific integration guides:

Referenceโ€‹

Complete API and configuration documentation:

Advancedโ€‹

Deep dives into internals and advanced topics:

Troubleshootingโ€‹

Solutions to common problems:

Language-Specific Resourcesโ€‹

JavaScript/TypeScriptโ€‹

Rubyโ€‹

Example Projectsโ€‹

Learn by example with complete working applications:

Quick Startโ€‹

JavaScript/TypeScriptโ€‹

import { Publisher, Subscriber } from "nats-pubsub";

// Publish a message
const publisher = new Publisher({
servers: "nats://localhost:4222",
env: "production",
appName: "my-app",
});

await publisher.publish("order.created", {
orderId: "12345",
amount: 99.99,
});

// Subscribe to messages
class OrderSubscriber extends Subscriber {
constructor() {
super("order.created");
}

async handle(message, metadata) {
console.log("Order created:", message);
}
}

// Start subscriber
const subscriber = new OrderSubscriber();
await subscriber.connect({
servers: "nats://localhost:4222",
env: "production",
appName: "my-app",
});

Rubyโ€‹

require 'nats_pubsub'

# Configure NatsPubsub
NatsPubsub.configure do |config|
config.servers = 'nats://localhost:4222'
config.env = 'production'
config.app_name = 'my-app'
end

# Publish a message
NatsPubsub.publish('order.created', {
order_id: '12345',
amount: 99.99
})

# Subscribe to messages
class OrderSubscriber < NatsPubsub::Subscriber
subscribe_to 'order.created'

def handle(message, context)
puts "Order created: #{message}"
end
end

# Start subscribers
NatsPubsub::Manager.start

Architecture Overviewโ€‹

Core Conceptsโ€‹

Topics and Subjectsโ€‹

NatsPubsub uses hierarchical topics with automatic subject generation:

{env}.{appName}.{topic}

Example: production.order-service.order.created

Reliability Patternsโ€‹

  • Outbox Pattern: Ensures messages are published even if NATS is temporarily unavailable
  • Inbox Pattern: Prevents duplicate message processing with database-backed deduplication
  • Dead Letter Queue: Automatically handles failed messages with configurable retry

Middleware Systemโ€‹

Add cross-cutting concerns with a composable middleware pipeline:

// JavaScript
subscriber.use(loggingMiddleware);
subscriber.use(retryMiddleware);
subscriber.use(metricsMiddleware);
# Ruby
class OrderSubscriber < NatsPubsub::Subscriber
use LoggingMiddleware
use RetryMiddleware
use MetricsMiddleware
end

Why NatsPubsub?โ€‹

vs. Raw NATS Clientโ€‹

FeatureRaw NATSNatsPubsub
Declarative APIโŒโœ…
Inbox/Outbox PatternsโŒ Manualโœ… Built-in
Schema ValidationโŒโœ…
Testing Utilitiesโš ๏ธ Limitedโœ… Comprehensive
Auto-TopologyโŒโœ…
Observabilityโš ๏ธ Basicโœ… Built-in
Framework IntegrationโŒโœ… Rails, Express, NestJS

vs. Kafkaโ€‹

  • โœ… Simpler Operations: No ZooKeeper, easier deployment
  • โœ… Lower Latency: Sub-millisecond message delivery
  • โœ… Built-in Request/Reply: Native support for synchronous patterns
  • โœ… Smaller Footprint: Single binary, minimal resource usage
  • โš ๏ธ Ecosystem: Smaller ecosystem than Kafka

vs. RabbitMQโ€‹

  • โœ… Performance: 2-10x higher throughput
  • โœ… Simplicity: Easier to configure and operate
  • โœ… Cloud Native: Better Kubernetes integration
  • โœ… At-Least-Once: Built into JetStream
  • โš ๏ธ Message Persistence: Different durability model

Community & Supportโ€‹

Performance Benchmarksโ€‹

NatsPubsub delivers production-grade performance:

OperationThroughputLatency (p99)
Publishing (sync)50K msgs/sec2ms
Publishing (batch)200K msgs/sec5ms
Subscribing100K msgs/sec<1ms
Inbox Check150K ops/sec<1ms
Outbox Relay80K msgs/sec10ms

See Performance Guide for optimization tips.

Production Readyโ€‹

NatsPubsub is built for production with:

  • โœ… Battle-tested: Used in high-throughput production systems
  • โœ… Comprehensive Testing: 95%+ code coverage
  • โœ… Type Safety: Full TypeScript support
  • โœ… Monitoring: Built-in metrics and health checks
  • โœ… Documentation: Extensive guides and API docs
  • โœ… Active Maintenance: Regular updates and security patches

Next Stepsโ€‹

  1. New to NatsPubsub? Start with Introduction
  2. Ready to code? Try the Quick Start (5 minutes)
  3. Building for production? Read the Deployment Guide
  4. Need help? Check Troubleshooting

License: MIT | Version: 1.0.0 | Last Updated: November 2025