Устойчивость request/reply
Order-svc не только публикует, но перед подтверждением заказа спрашивает inventory через orders.inventory.check. Здесь отказ особенно заметен: приложение ждёт ответа.
Core request/reply использует личный _INBOX. Префикс меняется через inboxPrefix в JS, CustomInboxPrefix в Go. Если _INBOX.> запрещён, оператор разрешает отдельный префикс, а клиент использует его; см. Авторизацию. Здесь разбирается отсутствие ответа и два разных исхода.
Две идеи: тайм-аут против no responders и безопасный повтор с backoff/идемпотентностью.
Три исхода запроса
Request отправляет тему и данные и ждёт до тайм-аута, задаваемого вызову либо соединению.
Успех — inventory отвечает в срок, приложение продолжает.
Тайм-аут означает отсутствие своевременного ответа, не обязательно отсутствие сервиса. Возможны долгий запрос БД, GC, перегрузка: сообщение дошло подписчику, но ответ опоздал.
No responders приходит немедленно: сервер знает об отсутствии подписки и отвечает статусом 503 без тела. Сервис не запущен, не зарегистрирован или находится за границей записи. Отвечать некому.
CLI выводит успешный ответ, при тайм-ауте выходит без него, при отсутствии — сразу No responders are available:
- CLI
- C
#!/bin/bash
# order-svc asks the inventory question and waits for a reply, with a
# timeout that bounds how long it blocks.
#
# A request has exactly three outcomes:
# - a reply arrives inside the deadline -> printed below
# - the deadline passes with no reply -> a timeout
# - no subscription is listening -> an immediate 503
# (no responders)
#
# --timeout sets the deadline. Keep it at two or three times the
# responder's p99 latency so a slow-but-healthy answer is not mistaken
# for a fault. Most client libraries surface the same three outcomes as a
# reply, a timeout error, and a no-responders error; Java needs the
# reportNoResponders() connect option and the future-based request to tell
# the two failures apart.
nats request orders.inventory.check \
'{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}' \
--timeout 2s
// Ask the inventory question with a two-second deadline. Exactly one
// of three things happens: a reply arrives in time, the deadline
// passes (NATS_TIMEOUT), or nobody is listening and the server says
// so at once (NATS_NO_RESPONDERS).
const char *order = "{\"order_id\":\"ord_8w2k\",\"customer\":\"acme-co\","
"\"total_cents\":4200,\"ts\":\"2026-05-22T10:14:22Z\"}";
natsMsg *reply = NULL;
s = natsConnection_RequestString(&reply, conn, "orders.inventory.check",
order, 2000);
switch (s)
{
case NATS_OK:
printf("inventory replied: %.*s\n",
natsMsg_GetDataLength(reply), natsMsg_GetData(reply));
natsMsg_Destroy(reply);
break;
case NATS_TIMEOUT:
// The responder is there but slow; no answer arrived in time.
printf("inventory did not answer within the deadline\n");
break;
case NATS_NO_RESPONDERS:
// Nothing subscribes to the subject; this returns immediately.
printf("no inventory responder is running\n");
break;
default:
printf("request failed: %s\n", natsStatus_GetText(s));
break;
}
Прежнее событие заказа:
{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}
Параметры клиента — в его API, сервер — в справочнике.
Польза no responders
Без сигнала запрос к пустой теме зря ждал бы, например, две секунды.
За один обмен клиент узнаёт отсутствие inventory и может подождать запуска. Тайм-аут допускает скорый повтор, отсутствующий сервис требует большей задержки.
Анимация сравнивает тайм-аут с повтором и немедленный no responders:
Нужен сервер с 503 и клиент с объявленной поддержкой; это давно стандарт. Проверьте тему без отвечающего:
- CLI
- C
#!/bin/bash
# See the no-responders signal for yourself.
#
# Request a subject that nobody is listening on. With no inventory
# responder running, the server knows immediately that no subscription
# exists on orders.inventory.check, and returns a 503 no-responders
# signal at once -- the request does NOT wait out the --timeout.
#
# Run this with no `nats reply orders.inventory.check ...` running, and
# the CLI prints the no-responders error right away. Start a responder
# and the same request gets an answer instead. Most client libraries
# surface this as a distinct no-responders error you can branch on,
# separate from a timeout; in Java you opt in with
# Options.Builder.reportNoResponders() and use the CompletableFuture-based
# request.
nats request orders.inventory.check \
'{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}' \
--timeout 2s
// Request a subject nobody is listening on. The server knows no
// subscription matches orders.inventory.check and sends back a 503
// at once: the call returns NATS_NO_RESPONDERS immediately instead
// of waiting out the two-second deadline.
const char *order = "{\"order_id\":\"ord_8w2k\",\"customer\":\"acme-co\","
"\"total_cents\":4200,\"ts\":\"2026-05-22T10:14:22Z\"}";
natsMsg *reply = NULL;
s = natsConnection_RequestString(&reply, conn, "orders.inventory.check",
order, 2000);
if (s == NATS_NO_RESPONDERS)
printf("no responders: the inventory service is not running\n");
else if (s == NATS_OK)
{
// Start a responder on orders.inventory.check and the same
// request gets an answer instead.
printf("inventory replied: %.*s\n",
natsMsg_GetDataLength(reply), natsMsg_GetData(reply));
natsMsg_Destroy(reply);
}
Разные повторы
Backoff увеличивает интервалы, давая перегруженному сервису восстановиться вместо лавины повторов.
Для тайм-аута — короткий ограниченный повтор, для no responders — экспоненциальная задержка до появления сервиса.
Цикл всегда ограничен, например пятью попытками, со случайным jitter против одновременного наплыва.
Нужна идемпотентность: исходный запрос мог выполниться, а ответ потеряться. Повтор не должен резервировать товар или списывать дважды.
Order-svc передаёт order_id ord_8w2k, inventory хранит недавние ID и возвращает прежний ответ вместо действия. Поле уже в нагрузке, дополнительного протокола нет; дисциплина обеих сторон.
Core не сохраняет запрос в момент разрыва. Inbox восстановится, после связи можно повторить. Идемпотентность защищает, если первый всё-таки дошёл.
Типичные ошибки
Ловушки различения и повторов:
Все ошибки одинаковы. Единый слепой повтор либо медлит при доступном сервисе, либо бомбит пустую тему. Разделите ошибки и интервалы.
Тайм-аут ниже реальной задержки. Измерьте p99 inventory, задайте в два-три раза больше, иначе повторы создаются при нормальных медленных ответах.
Бесконечный цикл. Ограничьте число, добавьте jitter и верните явную ошибку вызывающему с журналом.
Повтор с двойным действием. Всегда ключ order_id и устранение дублей у отвечающего.
Безопасный шаблон:
- CLI
- C
#!/bin/bash
# The safe retry pattern: branch on the failure, bound the retries, and
# key the request by order_id so a duplicate is a no-op on the responder.
#
# The CLI does not expose a per-failure backoff strategy the way the
# client libraries do (fast-retry-on-timeout vs
# exponential-backoff-on-no-responders). Here we show the same shape with
# a bounded loop and growing waits, and we keep the payload -- including
# its order_id -- byte-identical on every attempt so the inventory
# responder can de-dupe a re-sent request.
PAYLOAD='{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}'
MAX_ATTEMPTS=5
attempt=1
while [ "$attempt" -le "$MAX_ATTEMPTS" ]; do
# The CLI exits 0 even when no reply arrives (it logs "No responders are
# available" or silently gives up on timeout), so test for a reply body
# instead of the exit code. Same order_id on every attempt -> the responder
# treats a retry as the same question and returns the cached answer.
reply=$(nats request orders.inventory.check "$PAYLOAD" --timeout 2s --raw 2>/dev/null)
if [ -n "$reply" ]; then
echo "inventory check answered on attempt $attempt: $reply"
exit 0
fi
# Grow the wait, with a little jitter, so a fleet of requesters does not
# retry in lockstep and overwhelm the responder the instant it returns.
wait=$(( attempt * attempt ))
jitter=$(( RANDOM % 2 ))
echo "attempt $attempt failed; backing off ${wait}s before retry" >&2
sleep "$(( wait + jitter ))"
attempt=$(( attempt + 1 ))
done
echo "inventory check failed after $MAX_ATTEMPTS attempts; giving up" >&2
exit 1
// The safe retry: branch on the failure, bound the attempts, and keep
// the payload -- including its order_id -- identical on every attempt
// so the inventory responder can de-dupe a re-sent request.
const char *order = "{\"order_id\":\"ord_8w2k\",\"customer\":\"acme-co\","
"\"total_cents\":4200,\"ts\":\"2026-05-22T10:14:22Z\"}";
int maxAttempts = 5;
int attempt;
for (attempt = 1; attempt <= maxAttempts; attempt++)
{
natsMsg *reply = NULL;
s = natsConnection_RequestString(&reply, conn,
"orders.inventory.check",
order, 2000);
if (s == NATS_OK)
{
printf("inventory answered on attempt %d: %.*s\n", attempt,
natsMsg_GetDataLength(reply), natsMsg_GetData(reply));
natsMsg_Destroy(reply);
break;
}
else if (s == NATS_TIMEOUT)
{
// The responder is up but slow: a fast retry is reasonable.
fprintf(stderr, "attempt %d timed out, retrying shortly\n",
attempt);
nats_Sleep(200);
}
else if (s == NATS_NO_RESPONDERS)
{
// Nothing is listening yet: back off exponentially, with
// jitter so a fleet of requesters does not retry in lockstep.
int64_t wait = (1000 << (attempt - 1)) + (rand() % 250);
fprintf(stderr, "attempt %d found no responder, backing off "
"%dms\n", attempt, (int) wait);
nats_Sleep(wait);
}
else
break; // an unexpected error; do not keep retrying
}
if (s != NATS_OK)
fprintf(stderr, "inventory check failed after %d attempts: %s\n",
maxAttempts, natsStatus_GetText(s));
Что уже готово
Проверка inventory различает:
- Ответ, тайм-аут, немедленное отсутствие отвечающего.
- Короткие повторы и backoff с пределом и jitter.
- Идемпотентные запросы order_id после потери ответа или соединения.
Устойчивость есть, но канал и личность пока не защищены.
Что дальше
Загрузим creds order-svc и CA кластера для проверенного TLS.
Перейдите к TLS и аутентификации.
См. также
- Core NATS → Request/reply — inbox.
- Сервисы — обнаружение, endpoints и метрики.
- Справочник — протокол; параметры запросов в API клиента.