# Glossary — NATS JetStream (this repo)

The canonical vocabulary. Opinionated: where the repo has a house term, that wins; the general
industry term is noted so you can map to the interview. Adhere to these names in every lesson.

---

### NATS
A lightweight, high-performance messaging system — a single Go binary, in-memory-fast (<1ms typical),
built for microservice eventing. Here it's one of the two buses (the other is Kafka).

### core NATS
Plain publish/subscribe with **at-most-once** delivery: if no subscriber is listening when a message
is published, it's gone. No persistence. Fast fan-out for the "fire and forget" case.

### JetStream
NATS's built-in **persistence layer** on top of core NATS. It captures messages into **streams** and
replays them to **consumers**, adding **at-least-once** delivery, replay, dedup, and flow control.
This whole course is JetStream (the repo uses JetStream, not raw core NATS, for durable events).

### subject
The address a message is published to — a dotted hierarchy, PascalCase here (`Staff.Upserted`,
`User.Created`, `Notification.Created`). Subscribers express interest in subjects. (Interview: the
"topic" of NATS, but far more granular and hierarchical.)

### wildcard
A subject pattern: **`*`** matches exactly one token (`User.*` = `User.Created`, `User.Deleted`);
**`>`** matches the rest (`chat.chat.>` = everything under it). Streams here capture with wildcards;
consumers filter down to a concrete subject.

### publish/subscribe
One-to-many: a publisher sends on a subject, and *every* interested subscriber receives it. The
default NATS distribution model.

### queue group / deliver group
Load-balanced delivery: subscribers sharing a **queue group** get each message delivered to *exactly
one* of them (chosen by the server) — horizontal scaling of a consumer. In JetStream the durable
consumer's `DeliverGroup` field carries this. The repo's `QueueSubscribe` is the common path.

### stream
A JetStream's durable, ordered store of the messages published to a set of **subjects**. Has a
retention policy, storage type, replica count, and limits. Here streams are named lowercase
(`notification`, `staff`, `user`) and provisioned by the **fink** job.

### retention policy
When a stream deletes messages. **Limits** (default — delete on max age/bytes/msgs); **WorkQueue**
(delete once a consumer acks it — FIFO queue); **Interest** (keep a message only while a consumer
still needs it). **This repo uses `InterestPolicy` almost everywhere** — messages persist only as
long as an interested consumer hasn't consumed them.

### storage (file / memory)
Where a stream's messages live. **File** survives restarts (durable); **memory** is faster but
volatile. This repo uses file storage (`store_dir` in `nats.conf`).

### replicas
How many NATS servers hold a copy of the stream (RAFT quorum), for fault tolerance. **3** in prod
here; forced to **1** locally (`isLocal`).

### consumer
A stateful **view/cursor** on a stream for one subscriber (or queue group). It tracks delivery
position and pending acks, and has its own config: ack policy, `AckWait`, `MaxDeliver`, deliver
policy, filter subject. A stream can have many consumers, each at its own position.

### durable vs ephemeral
A **durable** consumer has an explicit name and survives disconnects — it remembers its position, so
a restarted service resumes where it left off. An **ephemeral** consumer vanishes when its subscriber
disconnects. The repo's consumers are **durable** (`Durable<Name>`).

### push vs pull
**Push:** the server delivers messages to the subscriber as they arrive (server-driven flow). **Pull:**
the client requests messages in batches (`Fetch`), controlling its own flow and load balancing. The
repo is **push queue-group everywhere** except the one **pull** consumer (zeus activity-log batch).

### deliver policy
Where a new consumer starts reading the stream: **DeliverAll** (from the beginning), **DeliverNew**
(only messages published after it's created), **DeliverLast**, by start-time, by start-sequence. The
learner services use **`DeliverNew()`** (don't replay history on first deploy).

### filter subject
The concrete subject a consumer receives from a wildcard stream. The stream captures `User.*`; a
consumer sets `FilterSubject = "User.Created"` to get only that one.

### ack policy / acknowledgement
How the consumer confirms it processed a message. **AckExplicit** (each message acked individually —
forced here), **AckAll** (ack N acks all before it), **AckNone** (no acks). Explicit ack is what makes
delivery **at-least-once**: unacked messages are redelivered.

### Ack / Nak / Term / InProgress
The four consumer replies. **Ack** = done, delete/advance. **Nak** = can't process now, redeliver
soon. **Term** = will never process, stop redelivering. **InProgress** = still working, reset the ack
timer. **This repo uses only `Ack`** — retryable failures redeliver via timeout (no `Nak`/`Term`).

### AckWait
How long the server waits for an ack before **redelivering** the message. On a retryable failure the
repo simply doesn't ack, so the message redelivers after `AckWait` (30s–300s per consumer; 2–4s locally).

### MaxDeliver
The maximum number of times a message is delivered before the server gives up. After `MaxDeliver` (3
or 10 here), the message is **dropped** — there's **no DLQ** in this repo (only metrics/logs).

### MaxAckPending
The cap on in-flight *unacked* messages per consumer — flow control / backpressure. 30 for
push-notification, 5000 for student-package sync, 100000 for the activity-log pull.

### `Nats-Msg-Id` / deduplication
A header stamped on every published message (here a **ULID**). JetStream's **dedup window** (default 2
min) drops a message whose `Nats-Msg-Id` it has already seen — publish-side idempotency.

### `DataInMessage` (the envelope)
The repo's proto wrapper around every published payload: `{Payload, ResourcePath, UserId, TraceInfo}`.
The business bytes ride in `Payload`; **tenancy** (`ResourcePath`/`UserId`) and **B3 trace** ride
alongside — and are re-injected into the consumer's `context` (via `ContextWithJWTClaims`) so **RLS
and tracing survive the async hop**. The single cleverest thing in the repo's NATS layer.

### `MsgHandler`
The subscriber callback signature: `func(ctx, data []byte) (retry bool, err error)`. The `retry`
bool decides redelivery: `err+retry=true` → don't ack → redeliver; `err+retry=false` → ack (drop the
poison message); success → ack.

### `SkipMsgOlderThan`
A consumer option that **skips and acks** messages older than a threshold (the learner services use
`aWeekAgo`) — protects against a replay storm after downtime.

### fink
The service/job that **provisions** NATS streams (and Kafka topics): `cmd/server/fink/upsert_streams_nats.go`
+ `streams/*.go`. It runs `UpsertStream` for every declared stream. Streams are provisioned here;
consumers are provisioned at subscribe time by the golib.

### `RegisterNatsSubscribers` / `NatsServicer`
The bootstrap hook a service implements to opt into NATS: `RegisterNatsSubscribers(ctx, cfg, *Resources)`.
Called at boot; where a service wires up all its subscribers. (From the Go-techstack course.)
