Плавное завершение
События сделали автомат наблюдаемым. Теперь выполним намеренный выход: при развёртывании, переносе пода или SIGTERM есть несколько секунд для чистого завершения.
Простой выход теряет очередь warehouse и ещё не отправленную публикацию order-svc. Сначала закончим незавершённое.
Различим close/drain и ограничение drain timeout, затем отдельную подписку и flush.
Close обрывает работу
Close сразу закрывает сокет без UNSUB и ожидания обработчиков. Библиотечный Close() пытается отправить буфер записи, но прекращает входящие доставки и удаляет reconnect buffer. SIGKILL теряет даже буфер записи.
Есть два вида незавершённого.
Входящие уже доставлены клиенту, но обработчик не закончил. Buffered orders.created при close не дойдут до warehouse.
Исходящие ещё в write buffer. Чистый Close обычно отправляет их; падение или SIGKILL уничтожает вместе с процессом.
Close уместен тестам и ненужным соединениям на ошибочном пути. Плановая остановка требует drain.
Drain завершает перед закрытием
Drain упорядоченно завершает работу. Обычно Drain(), в C# — dispose с DrainSubscriptionsOnDispose.
Две фазы: DRAINING_SUBS и DRAINING_PUBS видны в Go/Python. Сначала UNSUB всем подпискам и завершение полученного, затем отправка всех публикаций и close. Другие клиенты скрывают фазы внутри.
Порядок важен: остановить поступление, закончить работу, отправить результат и закрыть.
Анимация сопоставляет потерю при close с доработкой и flush при drain.
Drain по сигналу
В обработчике SIGTERM запускайте drain и ждите CLOSED перед выходом. Warehouse завершит очередь, order-svc отправит публикации.
Python/JS await nc.drain() ждёт конца. Go Drain() возвращает сразу: нужен ClosedHandler и ожидание. Выход сразу после возврата теряет работу.
CLI nats sub по Ctrl-C закрывается. Nats reply вызывает Drain, но выходит сразу, не ожидая фона: показывает место вызова, не полный надёжный шаблон. Код приложения должен ждать CLOSED.
- CLI
- C
#!/bin/bash
# Where the Drain() call belongs on shutdown, shown with `nats reply`.
#
# `nats reply` installs an interrupt handler that calls Drain() when you
# press Ctrl-C -- the right place for the call. It exits as soon as Drain()
# returns, though, without waiting for the drain to complete (nats.go drains
# in the background), so use it to see where the drain call belongs rather
# than to observe a finished drain. (`nats sub` has no such handler: Ctrl-C
# just terminates the process and abandons any in-flight messages.)
#
# In a client library the full pattern is Drain() wired to a
# SIGTERM handler that waits for CLOSED before the process exits.
nats reply "orders.lookup" \
'order ord_8w2k: shipped' \
--server nats://n1:4222 \
--connection-name warehouse
// SIGTERM arrived: drain instead of close. The connection stops
// new deliveries, lets in-flight handlers finish, flushes
// pending publishes, then closes.
s = natsConnection_Drain(conn);
// Drain returns immediately and runs in the background, so wait
// for CLOSED before the process exits -- exiting on Drain()'s
// return abandons the work drain was meant to save.
while ((s == NATS_OK) && !natsConnection_IsClosed(conn))
nats_Sleep(100);
printf("drain complete, exiting\n");
Прежнее событие заказа:
{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}
В DRAINING_SUBS публикации обычно допустимы, чтобы обработчики отправили ответы. В DRAINING_PUBS новые отклоняются, Go — ErrConnectionDraining. Публикация сразу после Drain гоняется с фазой, поэтому сначала прекращайте производство работы, drain последним.
Ограничение времени drain
Drain timeout не даёт зависшему обработчику удержать процесс. В Go/Python ограничивает подписки: остаток отбрасывается, затем flush и close. В Go финальный flush отдельно ограничен пятью секундами; Java переданный срок включает его. Go сообщает ErrDrainTimeout.
Стандарт Go 30 секунд. Выбирайте по самому медленному обработчику: секунда при пятиисекундной записи БД обрывает работу при каждом развёртывании.
- CLI
- C
#!/bin/bash
# Drain has a deadline. If in-flight handlers do not finish within the
# drain timeout (default 30s in nats.go), the remaining queued messages
# are discarded and the connection closes anyway, surfacing a
# drain-timeout error.
#
# The CLI does not expose a separate drain-timeout flag -- its global
# --timeout bounds how long a single operation waits. The point this
# snippet stands in for lives in client code: size the drain timeout to your
# slowest handler so a clean shutdown does not silently drop work.
#
# This publishes the canonical order event with a generous operation
# timeout so a slow handshake is not cut off mid-flush.
nats pub orders.created \
'{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}' \
--server nats://n1:4222 \
--connection-name order-svc \
--timeout 30s
// Size the drain timeout to the slowest handler, with margin: a
// two-second handler gets ten seconds, not a round one second. If
// the timeout fires, the messages left are discarded and the drain
// surfaces NATS_TIMEOUT instead of completing. The default, with
// natsConnection_Drain(), is 30 seconds.
if (s == NATS_OK)
s = natsConnection_DrainTimeout(conn, 10000);
// Wait for CLOSED: only then has the drain finished (or been cut
// short by the timeout).
while ((s == NATS_OK) && !natsConnection_IsClosed(conn))
nats_Sleep(100);
if (s == NATS_OK)
printf("drained within the timeout, nothing dropped\n");
Точные API — в библиотеке, сервер — в справочнике.
Drain одной подписки
Можно вывести одну подписку, сохранив остальные и соединение: UNSUB, затем завершение её очереди.
Типично для одного участника группы очереди warehouse: он дорабатывает свои заказы, остальные получают новые.
Go Subscription.Drain(), JS/Python sub.drain(), Java Subscription/Dispatcher drain(Duration) с future. Rust Subscriber::drain() отписывает сразу, поток заканчивается после остатка.
C# отдельного drain нет: dispose подписки завершает канал и теряет сообщения в пути. У соединения включите DrainSubscriptionsOnDispose, стандарт false: UNSUB, PING/PONG с DrainPingTimeout, стандарт пять секунд, затем завершение каналов. Для настоящей работы включайте.
CLI не демонстрирует отдельную подписку: nats sub имеет одну и закрывает по Ctrl-C. Пример запускает участника warehouse:
- CLI
- C
#!/bin/bash
# Rotating one queue-group member out without dropping its in-flight
# orders is a per-subscription drain: unsubscribe, finish the messages
# already buffered for that subscription, and leave the connection and
# every other subscription alive.
#
# The CLI cannot express it -- `nats sub` holds exactly one subscription
# and Ctrl-C closes rather than drains. This runs one warehouse member
# of the queue group; the drain call that rotates it out is a
# client-library call.
nats sub "orders.>" \
--queue warehouse \
--server nats://n1:4222 \
--connection-name warehouse-2
// One member of the warehouse queue group, sharing the orders.>
// load with the other members.
if (s == NATS_OK)
s = natsConnection_QueueSubscribe(&sub, conn, "orders.>",
"warehouse", onMsg, NULL);
// Rotate this member out without dropping its in-flight orders:
// drain the subscription, not the connection. It unsubscribes, so
// the server routes new orders to the remaining members, and the
// handler finishes what is already buffered here.
if (s == NATS_OK)
s = natsSubscription_Drain(sub);
// The drain runs in the background; block until it completes (zero
// means no timeout), then check how it ended.
if (s == NATS_OK)
s = natsSubscription_WaitForDrainCompletion(sub, 0);
if (s == NATS_OK)
s = natsSubscription_DrainCompletionStatus(sub);
// The connection and every other subscription are still alive.
if (s == NATS_OK)
printf("member rotated out, connection still %s\n",
natsConnection_IsClosed(conn) ? "closed" : "open");
Flush
Flush — PING с ожиданием PONG. Сервер обрабатывает по порядку, поэтому ответ доказывает получение предшествующих публикаций. Это отдельный барьер без закрытия.
Он не доказывает доставку подписчику или сохранение: последнее подтверждает PubAck JetStream.
Go Flush() ждёт до десяти секунд, FlushTimeout() — ваш срок. Python nc.flush(), Java flush(Duration), JS await nc.flush(). C# PingAsync() делает обмен и возвращает время. Rust client.flush() ждёт лишь передачи байтов сокету, не PONG: получение сервером не подтверждает.
Drain уже включает flush. Отдельный нужен после серии публикаций перед признанием отправки либо перед close на ошибочном пути.
RTT использует тот же обмен: Go RTT(), Python/JS rtt(), Java RTT(), C# PingAsync(). Rust async не имеет ни RTT, ни round-trip flush. CLI nats rtt усредняет пять обменов каждого сервера; flush отдельной команды не имеет:
- CLI
- C
#!/bin/bash
# Flush is a client-library call: a PING the server answers with a PONG,
# confirming the server received everything the client wrote before it.
# The CLI has no flush command; the closest observable is `nats rtt`,
# the same PING/PONG round trip reported as a duration.
#
# For each server it can reach, `nats rtt` runs five round trips and
# prints the averaged time per resolved address.
nats rtt --server nats://n1:4222,nats://n2:4222,nats://n3:4222
// A burst of fire-and-forget publishes: the orders may still sit in
// the client's write buffer.
for (i = 0; (s == NATS_OK) && (i < 3); i++)
s = natsConnection_PublishString(conn, "orders.created",
"{\"order_id\":\"ord_8w2k\",\"customer\":\"acme-co\","
"\"total_cents\":4200,\"ts\":\"2026-05-22T10:14:22Z\"}");
// Flush sends a PING and waits for the PONG. The server processes a
// connection's traffic in order, so when this returns the server
// has received every publish above. natsConnection_Flush() is the
// same call with a default 10-second bound.
if (s == NATS_OK)
s = natsConnection_FlushTimeout(conn, 5000);
if (s == NATS_OK)
printf("flushed: the server has the batch\n");
Сервер уходит первым
Lame duck в INFO с ldm предупреждает о скорой остановке. Клиент может заранее остановить публикации и перейти на другой узел.
Connect_urls исключает уходящий сервер. Discovery и no_advertise рассмотрены раньше.
Callback — одно из событий. Причины ухода — Топологии; для клиента это подсказка.
Типичные ошибки
Три потери при остановке:
Публикация после Drain. Операция необратима, финальное событие может пройти либо получить ErrConnectionDraining. Не рассчитывайте на гонку, прекращайте производство раньше.
Обрабатывайте отказ явно:
- CLI
- C
#!/bin/bash
# Publishing after drain is a race, not a clean rejection. Drain runs in
# two phases: while the client is draining its subscriptions it still
# accepts a publish (so a handler can reply), and only once it moves on to
# flushing publishes does a new publish come back with a draining error
# (ErrConnectionDraining in nats.go, the equivalent in each library). A
# publish issued right after Drain() may slip through or may be rejected.
#
# The nats CLI has no scriptable "publish after drain" path: once it
# unsubscribes on Ctrl-C it exits, so there is no later publish to reject.
# The CLI cannot race a drain, so this snippet only carries the message
# shape. The teaching point is for client code: handle the draining
# error from a publish issued after Drain() instead of assuming the call
# succeeded -- drain last, after the application has stopped producing. Do
# not interleave a final "shutting down" publish with the shutdown.
nats pub orders.created \
'{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}' \
--server nats://n1:4222 \
--connection-name order-svc
const char *order = "{\"order_id\":\"ord_8w2k\",\"customer\":\"acme-co\","
"\"total_cents\":4200,\"ts\":\"2026-05-22T10:14:22Z\"}";
// Drain cannot be reversed. Once it starts, a publish is racing the
// drain's phases: it may slip through while subscriptions drain, or
// come back with NATS_DRAINING once the connection is flushing
// publishes.
s = natsConnection_Drain(conn);
if (s != NATS_OK)
fprintf(stderr, "drain failed: %s\n", natsStatus_GetText(s));
// A "shutting down" event published after Drain() cannot count on
// either outcome. Handle the draining error instead of assuming the
// publish succeeded -- and in real code, drain last, after the
// application has stopped producing.
s = natsConnection_PublishString(conn, "orders.created", order);
if ((s == NATS_DRAINING) || (s == NATS_CONNECTION_CLOSED))
fprintf(stderr, "publish rejected, connection is draining: %s\n",
natsStatus_GetText(s));
else if (s == NATS_OK)
printf("publish slipped through before the drain reached publishes\n");
Короткий drain timeout. Он выбрасывает незавершённое. Измерьте медленную работу и оставьте запас.
Drain не подтверждает JetStream за вас. Обработчик analytics должен отправить ack до закрытия, иначе сообщение повторится. Позиция — задача JetStream, не канала.
Что уже готово
SIGTERM вызывает drain, очередь обрабатывается, публикации отправляются, зависание ограничено. Один warehouse выходит без остановки группы. Flush проверяет получение без закрытия. Соединение переживает и внешний отказ, и плановый выход собственного процесса.
Что дальше
Внутреннее отставание обработчика наполняет буфер — медленный потребитель, без ограничений угрожающий памяти.
Перейдите к Медленным потребителям.
См. также
- Подтверждения JetStream.
- Публикация — хранение, в отличие от flush.
- Группы очередей.
- Первый кластер — lame duck.
- Справочник — протокол; клиентские сроки в API библиотеки.