not accepting clients
back to blog

patterns with nats

work queues, last-value caches, event sourcing, per-key ordering, scheduled messages and leases are each a stream or consumer setting on the nats server that is already running.

nats goes in for pub/sub. a few months later the same team needs a job queue, then a dashboard that knows the last state of every device, then a reminder that goes out three days after an invoice, then a lock so the nightly report runs on one replica out of three. each request comes with a proposal attached: redis for the queue and the lock, a cron sidecar for the reminder, kafka for anything that has to stay in order. that is three more systems to deploy, secure, back up and get paged for.

most of what those requests need is already in the nats server. jetstream, its persistence layer, has a handful of stream and consumer settings that combine into the usual messaging patterns, and each combination is a few lines of config.

this post goes through ten of them. the sections stand on their own, so it is fine to skip to the one that matches the request at hand. it builds on messaging with nats, which covers subjects, queue groups, streams, consumers and acks. the examples use nats.go 1.54 against nats-server 2.14 or later.

the short version

each pattern, what it is for, and the settings it is built from:

pattern what it is for built from
work queues jobs that are done once and then gone a stream with WorkQueuePolicy
acknowledged fan-out an event several services each have to finish a stream with InterestPolicy
last-value cache the current state of every key, without the history MaxMsgsPerSubject: 1 and DeliverLastPerSubjectPolicy
event sourcing state rebuilt from a log that concurrent writers share a subject per aggregate and WithExpectLastSequencePerSubject
per-key ordering parallel workers that keep each customer’s events in order a partition() subject transform and MaxAckPending: 1
single active consumer a handler that runs on one replica at a time PriorityPolicyPinned on the consumer
scheduled messages a message that goes out later, or on a cron AllowMsgSchedules with WithScheduleAt or WithScheduleCron
scatter-gather one question, answered by every instance a core request with no queue group, gathered until a deadline
leases a job that runs on one replica out of several kv.Create with KeyTTL
store-and-forward a site that keeps working while its uplink is down a leaf node with its own jetstream domain, sourced by the hub

work queues

a job queue holds each job until a worker finishes it, and gives each job to one worker. a default stream does neither: with LimitsPolicy it keeps messages until they age out or the stream fills, however many consumers have read them. WorkQueuePolicy deletes a message as soon as a consumer acks it, so the stream holds the outstanding work and nothing else:

stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name:      "JOBS",
	Subjects:  []string{"jobs.>"},
	Retention: jetstream.WorkQueuePolicy,
	Replicas:  3,
})
if err != nil {
	return err
}

cons, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
	Durable:       "thumbnails",
	FilterSubject: "jobs.thumbnail",
	AckPolicy:     jetstream.AckExplicitPolicy,
	AckWait:       2 * time.Minute,
	MaxDeliver:    5,
})

every replica of the worker pulls from the same durable consumer, thumbnails, and the server hands each message to one of them. a job that is not acked within AckWait is handed out again, up to MaxDeliver times.

the message count in nats stream info JOBS is the queue depth: jobs waiting plus jobs in flight. there is no consumer lag to work out.

the server enforces the policy by refusing any consumer that could receive a message another consumer already gets:

  • a second consumer whose filter overlaps the first: filtered consumer not unique on workqueue stream
  • a second consumer with no filter: multiple non-filtered consumers not allowed on workqueue stream
  • a consumer that does not start at the beginning: consumer must be deliver all on workqueue stream

so each job type gets its own filter and its own consumer: jobs.thumbnail for one, jobs.transcode for the next.

acknowledged fan-out

three services each need every issued invoice: accounting, the email sender and the audit log. the stream should let go of an invoice once all three are done with it. a limits stream keeps it for MaxAge whether anyone read it or not. InterestPolicy keeps it until every consumer whose filter matches has acked it:

stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name:      "INVOICES",
	Subjects:  []string{"invoices.>"},
	Retention: jetstream.InterestPolicy,
	Replicas:  3,
	MaxAge:    7 * 24 * time.Hour,
})
if err != nil {
	return err
}

for _, name := range []string{"accounting", "email", "audit"} {
	_, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
		Durable:       name,
		FilterSubject: "invoices.issued",
		AckPolicy:     jetstream.AckExplicitPolicy,
	})
	if err != nil {
		return err
	}
}

the stream’s size now tracks the slowest of the three consumers. MaxAge stays on as a ceiling, for the day one of them stops acking altogether.

interest works the other way too. a message that no consumer’s filter matches is skipped on arrival: the publish is acked and assigned a sequence number, and nothing is stored. here that applies to everything on invoices.> other than invoices.issued.

last-value cache

devices publish their state to devices.<id>.state every few seconds. a dashboard needs the current state of every device when it starts, and has no use for the history. MaxMsgsPerSubject: 1 keeps one message per subject, so each new state replaces the one before it:

stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name:              "DEVICES",
	Subjects:          []string{"devices.*.state"},
	MaxMsgsPerSubject: 1,
	AllowDirect:       true,
	Replicas:          3,
})

looking up one device is a single read. AllowDirect lets any replica answer it, so lookups do not all queue up at the stream leader:

msg, err := stream.GetLastMsgForSubject(ctx, "devices.pump-07.state")

the dashboard wants all of them. an ordered consumer, which is ephemeral and managed by the client library, starts at the last message of every subject and then carries on with live updates:

cons, err := stream.OrderedConsumer(ctx, jetstream.OrderedConsumerConfig{
	DeliverPolicy: jetstream.DeliverLastPerSubjectPolicy,
})
if err != nil {
	return err
}

cc, err := cons.Consume(func(msg jetstream.Msg) {
	state.apply(msg.Subject(), msg.Data())

	if meta, err := msg.Metadata(); err == nil && meta.NumPending == 0 {
		state.markReady()
	}
})

NumPending is the number of messages still to come. when it reaches zero the replay has caught up and everything after it is a live update, the same boundary the key-value watcher marks with a nil entry. an empty stream never delivers a message to count down on, so a dashboard that waits for that moment checks stream.CachedInfo().State.Msgs first.

the kv store is this pattern with a friendlier api. the stream is the better fit when devices already publish to subjects of their own and moving them to kv.Put is not on the table.

event sourcing

event sourcing stores what happened instead of the current state. an order is the list of everything that happened to it, and its current state is those events applied in order.

the thing the events belong to is called the aggregate, here the order. a subject per aggregate gives each order its own list inside one stream:

stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name:       "ORDER_EVENTS",
	Subjects:   []string{"orders.events.*"},
	Replicas:   3,
	DenyDelete: true,
	DenyPurge:  true,
})

DenyDelete and DenyPurge make the log append-only through the api. loading an order means replaying its subject up to the newest event. the function looks that event up first, so it knows where to stop:

func load(ctx context.Context, stream jetstream.Stream, id string) (Order, uint64, error) {
	var order Order
	subject := "orders.events." + id

	last, err := stream.GetLastMsgForSubject(ctx, subject)
	if errors.Is(err, jetstream.ErrMsgNotFound) {
		return order, 0, nil
	}
	if err != nil {
		return order, 0, err
	}

	cons, err := stream.OrderedConsumer(ctx, jetstream.OrderedConsumerConfig{
		FilterSubjects: []string{subject},
	})
	if err != nil {
		return order, 0, err
	}

	for {
		msg, err := cons.Next(jetstream.FetchMaxWait(5 * time.Second))
		if err != nil {
			return order, 0, err
		}
		order.apply(msg.Data())

		meta, err := msg.Metadata()
		if err != nil {
			return order, 0, err
		}
		if meta.Sequence.Stream >= last.Sequence {
			return order, last.Sequence, nil
		}
	}
}

the sequence it returns works as the order’s version. appending an event sends that version along as an expectation, and the stream refuses the write if anything else landed on the subject in between. this is optimistic concurrency: nothing is locked, and a writer that lost the race finds out when it writes.

_, err = js.Publish(ctx, "orders.events."+id, event,
	jetstream.WithExpectLastSequencePerSubject(version))
if isConflict(err) {
	// another writer got there first. reload the order and decide again.
}

version 0 means “no events yet”, so two writers creating the same order conflict the same way. the conflict comes back as one of two error codes:

// isConflict reports a failed expectation. a stale version is refused with
// 10071; on a replicated stream, a write that races another write to the same
// subject still in flight is refused with 10164. both mean reload and retry.
func isConflict(err error) bool {
	var apiErr *jetstream.APIError
	return errors.As(err, &apiErr) &&
		(apiErr.ErrorCode == jetstream.JSErrCodeStreamWrongLastSequence ||
			apiErr.ErrorCode == jetstream.JSErrCodeStreamWrongLastSequenceConstant)
}

one case looks like a conflict and is not. a publish can land and lose only its ack on the way back. the retry then reports a conflict as well, since the first attempt moved the version. WithMsgID, the usual way to make a retry safe, does not settle it everywhere: a replicated stream checks for duplicates first and acks the retry as one, while a single server checks the version first and refuses it. putting the command’s id in the event works on both: if the newest event after a reload carries the same id, the command already succeeded.

projections, the read models built from the events, are ordinary durable consumers on orders.events.*. adding a read model means adding a consumer that starts at the beginning of the stream.

per-key ordering

a consumer shared by three replicas processes messages in parallel, so two payments for the same customer can be handled out of order. MaxAckPending: 1, one unacked message at a time, restores the order and caps the whole stream at one message in flight.

the middle ground is what kafka does with partitions: split the subjects into partitions, keep each partition in order, and run the partitions in parallel.

a subject transform on the stream does the split. partition() hashes a token of the incoming subject into a fixed number of buckets, and the message is stored under the transformed subject. partition(4,1) is four buckets, hashed on the first wildcard, which here is the customer id:

stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name:     "PAYMENTS",
	Subjects: []string{"payments.*.*"},
	SubjectTransform: &jetstream.SubjectTransformConfig{
		Source:      "payments.*.*",
		Destination: "payments.{{partition(4,1)}}.{{wildcard(1)}}.{{wildcard(2)}}",
	},
	Replicas: 3,
})
if err != nil {
	return err
}

for p := 0; p < 4; p++ {
	_, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
		Durable:       fmt.Sprintf("payments-p%d", p),
		FilterSubject: fmt.Sprintf("payments.%d.>", p),
		AckPolicy:     jetstream.AckExplicitPolicy,
		MaxAckPending: 1,
		MaxDeliver:    5,
	})
	if err != nil {
		return err
	}
}
publish payments.c-1042.captured ─▶ subject transform ─▶ payments.2.c-1042.captured
                                    partition(4,1) hashes c-1042 into bucket 2

  payments.0.>  ─▶ payments-p0  max ack pending 1 ─┐
  payments.1.>  ─▶ payments-p1  max ack pending 1 ─┤
  payments.2.>  ─▶ payments-p2  max ack pending 1 ─┼─▶ every replica pulls from all four
  payments.3.>  ─▶ payments-p3  max ack pending 1 ─┘

publishers keep sending payments.<customer>.<event> and never learn the partition. every event for c-1042 hashes to the same bucket and lands on the same consumer. that consumer will not deliver the next message until the current one is acked, whichever replica is holding it.

at most four messages are in flight at once, one per partition, so the partition count is the number to size up front.

single active consumer

some consumers should only run in one place at a time: a handler that drives an upstream api allowing a single session per account, or one that batches writes in memory and flushes them in order. a pinned priority group lets every replica attach while the server delivers to only one of them:

cons, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
	Durable:        "ledger",
	AckPolicy:      jetstream.AckExplicitPolicy,
	PriorityPolicy: jetstream.PriorityPolicyPinned,
	PriorityGroups: []string{"ledger"},
	PinnedTTL:      30 * time.Second,
})
if err != nil {
	return err
}

cc, err := cons.Consume(handle, jetstream.PullPriorityGroup("ledger"))

the server pins the first client that pulls and leaves the others waiting as standbys. when the pinned client stops pulling for PinnedTTL, because it crashed or its node went away, the server pins the next one. for this one consumer, that replaces a separate leader election.

priority groups have two more policies. PriorityPolicyOverflow arrived with pinning in nats-server 2.11 and serves a client only once the backlog passes a threshold the client sets. PriorityPolicyPrioritized, added in 2.12, prefers clients by a priority number.

scheduled messages

a reminder due in three days can be published today. AllowMsgSchedules lets a stream hold a message until a set time and then publish it itself. the stream below takes two kinds of subject: reminders.schedule.* for schedules that are waiting, and reminders.due.* for reminders that have come due:

stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name:              "REMINDERS",
	Subjects:          []string{"reminders.schedule.*", "reminders.due.*"},
	AllowMsgSchedules: true,
	Replicas:          3,
})
if err != nil {
	return err
}

_, err = js.Publish(ctx, "reminders.schedule.invoice-1042", payload,
	jetstream.WithScheduleAt(time.Now().Add(72*time.Hour)),
	jetstream.WithScheduleTarget("reminders.due.invoice-1042"))

the message waits on its schedule subject until the time comes. then the server publishes it to the target and removes the schedule. consumers filter on reminders.due.* and never see the waiting ones.

each schedule needs a subject of its own. publishing to the same schedule subject again replaces the earlier schedule, and purging the subject cancels it, which is how “the invoice was paid, never mind” is written:

err = stream.Purge(ctx, jetstream.WithPurgeSubject("reminders.schedule.invoice-1042"))

a recurring schedule is the same publish with an interval or a six-field cron expression in place of a time. the first field is seconds, so this one fires at 06:00 every day:

_, err = js.Publish(ctx, "reminders.schedule.daily-digest", nil,
	jetstream.WithScheduleCron("0 0 6 * * *"),
	jetstream.WithScheduleTimeZone("Europe/Amsterdam"),
	jetstream.WithScheduleTarget("reminders.due.daily-digest"))

the target has to be a subject the same stream captures, and it cannot be the schedule subject itself. a schedule is a message in the stream, so it is replicated like any other and survives a node failure.

scatter-gather

some questions go to every instance at once: each warehouse’s stock of a sku, each cache’s hit rate. request-reply on a queue group gets one answer from one instance. without a queue group every subscriber receives the request, and every one of them can answer. gathering those answers takes a private inbox, a subject only the caller listens on, and a deadline:

func gather(nc *nats.Conn, subject string, data []byte, wait time.Duration) ([]*nats.Msg, error) {
	inbox := nc.NewInbox()
	sub, err := nc.SubscribeSync(inbox)
	if err != nil {
		return nil, err
	}
	defer sub.Unsubscribe()

	if err := nc.PublishRequest(subject, inbox, data); err != nil {
		return nil, err
	}

	var replies []*nats.Msg
	deadline := time.Now().Add(wait)
	for {
		msg, err := sub.NextMsg(time.Until(deadline))
		if errors.Is(err, nats.ErrTimeout) {
			return replies, nil
		}
		if err != nil {
			return replies, err
		}
		if msg.Header.Get("Status") == "503" {
			return replies, nats.ErrNoResponders
		}
		replies = append(replies, msg)
	}
}

the loop collects replies until the deadline passes and returns what it has. when nothing is subscribed to the subject, the server answers on the inbox itself with a 503 status, the same signal a plain request turns into nats.ErrNoResponders.

the micro package in nats.go is built on this. a service registered with micro.AddService answers $SRV.PING, $SRV.INFO and $SRV.STATS alongside its own endpoints, and nats micro ls is a scatter-gather over every running instance.

leases

a nightly job on three replicas should run once. a lease handles that: the replica that creates a key first runs the job, and the others see the key and stand down. kv.Create only succeeds when the key is absent or deleted, and with a ttl the key removes itself if its holder dies without cleaning up:

kv, err := js.CreateOrUpdateKeyValue(ctx, jetstream.KeyValueConfig{
	Bucket:         "leases",
	Replicas:       3,
	LimitMarkerTTL: time.Minute,
})
if err != nil {
	return err
}

rev, err := kv.Create(ctx, "nightly-report", []byte(hostname),
	jetstream.KeyTTL(15*time.Minute))
if errors.Is(err, jetstream.ErrKeyExists) {
	return nil // another replica has it
}
if err != nil {
	return err
}
defer kv.Delete(ctx, "nightly-report", jetstream.LastRevision(rev))

return runReport(ctx)

the deferred delete hands the lease back when the report finishes. LastRevision makes it conditional, so a replica whose lease has already expired cannot delete the next holder’s key.

per-key ttls need LimitMarkerTTL on the bucket and nats-server 2.11. the marker is what the server writes when a key expires, so a watcher sees the lease end as a purge.

store-and-forward

a till in a shop has to keep taking payments when the shop’s uplink drops. the fix is a nats server in the shop itself, running as a leaf node: a server that connects out to the central cluster, the hub, and bridges subjects between the two. with a jetstream domain of its own, its streams are stored in the shop and stay writable while the hub is out of reach:

# shop-042.conf - the leaf node in the shop
jetstream {
  domain: shop-042
  store_dir: /var/lib/nats
}

leafnodes {
  remotes: [
    { url: "nats-leaf://hub.example.com:7422", credentials: "/etc/nats/shop-042.creds" }
  ]
}

the till publishes into a stream on the leaf, which has a single server and so a single replica:

_, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name:     "SALES",
	Subjects: []string{"sales.shop-042.>"},
	MaxAge:   14 * 24 * time.Hour,
})

in the hub, one stream copies that stream from every shop’s domain. Sources is the setting that does the copying:

_, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
	Name: "SALES",
	Sources: []*jetstream.StreamSource{
		{Name: "SALES", Domain: "shop-042"},
		{Name: "SALES", Domain: "shop-043"},
	},
	Replicas: 3,
})
  shop-042, leaf node                           hub
  ┌──────────────────────────────┐          ┌──────────────────────────────┐
  │ till ─▶ sales.shop-042.>     │          │ stream SALES                 │
  │         stream SALES         │ ───────▶ │   source SALES @ shop-042    │
  │         keeps writing while  │ leafnode │   source SALES @ shop-043    │
  │         the uplink is down   │          │   ...                        │
  └──────────────────────────────┘          └──────────────────────────────┘

the hub reads each shop’s stream through a consumer it creates over the leaf connection. when the uplink drops, the shop keeps appending locally and the hub stops reading. when it comes back, the source resumes from the last sequence it copied. the shop stream’s MaxAge and MaxBytes set the longest outage the shop survives without losing a sale, so they are sized for the worst uplink in the estate.

what to watch out for

a work queue has room for one consumer per subject. that rules out attaching a consumer to a live work queue to see what is in it. reading by sequence, with stream.GetMsg or nats stream get, consumes nothing and works on any stream.

interest streams throw away messages nobody is listening for. the consumers have to exist before the first publish, so they belong in the same deploy step that creates the stream, not in each consumer’s own startup. the reverse also holds: a durable someone created to debug and never deleted counts as interest, and holds every message it matches until MaxAge.

the conflict error has two codes. a stale version is refused with 10071. on a replicated stream, a write that arrives while another write to the same subject is still being proposed is refused with 10164 instead. code that only checks 10071 passes every sequential test and misses the concurrent case, which is the one optimistic concurrency is there for. kv.Create and kv.Update already map both, to ErrKeyExists and ErrKeyRevisionMismatch.

a poison message stalls its partition. with MaxAckPending: 1, a message whose handler keeps failing blocks everything behind it in the same partition until MaxDeliver runs out. MaxDeliver defaults to unlimited, which makes the stall permanent, so the partition consumers above set it. the max-deliveries advisory, covered in messaging with nats, is where the dropped message gets copied to a dead-letter subject.

MaxAckPending: 1 only keeps order while handlers finish inside AckWait. a handler that overruns it gets its message redelivered, possibly to another replica, while the first copy is still running. a long handler calls msg.InProgress() to reset the timer.

the partition count is part of the hash. changing partition(4,1) to partition(8,1) moves most customers to a different partition, and their in-flight events can be processed on both sides of the change at once. draining the consumers before changing the transform keeps per-key order intact.

scheduling depends on the server version. delayed @at schedules shipped in nats-server 2.12 and recurring ones in 2.14. a scheduling stream cannot use DiscardNew, and the server turns on AllowRollup for it, since replacing a schedule is a rollup of its subject.

scatter-gather cannot know how many replies are coming. the deadline decides, and a responder slower than the deadline is missing from the result with nothing to say so. a caller that needs a complete answer has to know the expected set, the list of warehouses for example, and compare against it.

a lease is not a fence. a process that stalls past its KeyTTL, in a long gc pause or a frozen vm, wakes up still believing it holds the lease while another replica has taken it. anything the job writes should carry the lease revision, so the receiving side can reject writes from an older holder.

references

[1] nats documentation. “jetstream streams - retention policies.”
docs.nats.io/nats-concepts/jetstream/streams

[2] nats documentation. “subject mapping and partitioning.”
docs.nats.io/nats-concepts/subject_mapping

[3] nats documentation. “headers - expected last subject sequence.”
docs.nats.io/nats-concepts/jetstream/headers

[4] nats-io. “adr-42: pull consumer priority groups.”
github.com/nats-io/nats-architecture-and-design/blob/main/adr/adr-42.md

[5] nats-io. “adr-51: jetstream message scheduler.”
github.com/nats-io/nats-architecture-and-design/blob/main/adr/adr-51.md

[6] nats. “nats server 2.14 release.”
nats.io/blog/nats-server-2.14-release

[7] nats documentation. “leaf nodes.”
docs.nats.io/running-a-nats-service/configuration/leafnodes

[8] nats documentation. “source and mirror streams.”
docs.nats.io/nats-concepts/jetstream/source_and_mirror

[9] nats-io. “nats.go - micro.”
github.com/nats-io/nats.go/tree/main/micro