Topics
Topics provide scalable, decoupled, asynchronous messaging between services. When a message is published to a topic, it's immediately pushed to all subscribers, making topics perfect for real-time event processing.
Quick Start
Here's a minimal example to get you started:
import { topic } from '@nitric/sdk'const userCreatedTopic = topic('user-created').allow('publish')// Publish a messageawait userCreatedTopic.publish({email: 'new.user@example.com',})// Subscribe to messagesuserCreatedTopic.subscribe(async (ctx) => {const { email } = ctx.req.json()console.log(`New user created: ${email}`)})
Core Concepts
Topics
A topic is a named resource where events can be published. Topics enable real-time communication between services, with messages being pushed to subscribers as soon as they're published.
Subscriptions
A subscription is a binding between a topic and a service. When a message is published to a topic, all subscribers receive a copy of the message.
Permissions
Topics require explicit permissions for operations:
publish
: Send messages to the topicsubscribe
: Receive messages from the topic
Common Operations
Publishing Messages
const topic = topic('my-topic').allow('publish')await topic.publish({message: 'Hello subscribers!',})
Subscribing to Messages
const topic = topic('my-topic')topic.subscribe(async (ctx) => {const { message } = ctx.req.json()console.log(`Received: ${message}`)})
Cloud Provider Support
Each cloud provider comes with a set of default services used when deploying resources. You can find the default services for each cloud provider below.
Topics are mapped to SNS in AWS. For more details about the AWS implementation, including configuration options and limitations, see the AWS Topics documentation.
When running locally, topics use a local implementation for development and testing.
For best practices and patterns when working with topics, including handling message delivery guarantees and idempotency, see our Async Messaging Patterns Guide.