Размещение
ORDERS уже работает с R=3 в east, но три сервера выбрал лидер метаданных — любые с достаточным местом.
Теперь вы управляете тем, где находятся реплики: в определённом кластере или на серверах с назначенными метками. Это не меняет нагрузку или темы публикаций order-svc.
Размещение ограничивает серверы реплик
Размещение — правило потока, ограничивающее допустимые серверы реплик. Без него лидер метаданных свободно выбирает узлы east. С ним он обязан выполнить условия либо отказать в создании.
Первый рычаг — кластер: все реплики должны находиться в указанном кластере. Для единственного east это ничего не меняет. Привязка к региону в многокластерной системе разобрана в Суперкластерах.
Внутри east важен второй рычаг — метки.
Метки задаются серверам и проверяются размещением
Метка — произвольный текст в конфигурации сервера: регион, класс диска, уровень оборудования. Сервер объявляет её остальным, а размещение использует для отбора.
Метки задаются через server_tags. Назначьте трём рабочим серверам регион и класс диска:
# n1-east.conf — tag this server for placement
server_name: n1-east
listen: "0.0.0.0:4222"
server_tags: ["region:us-east", "disk:ssd"]
cluster {
name: east
listen: "0.0.0.0:6222"
routes: [
"nats://127.0.0.1:6223"
"nats://127.0.0.1:6224"
]
}
jetstream { store_dir: "/data/n1-east" }
Повторите server_tags на n2-east и n3-east, сохраняя собственные server_name, порты и store_dir. После перезапуска проверьте результат. nats server info требует системную запись $SYS; см. Формирование кластера. Указывайте имя сервера, иначе ответит первый участник $SYS ping:
nats server info n1-east
Строка Tags показывает фактические метки. Проверяйте её: опечатка в server_tags остаётся незаметной до запроса отсутствующей метки.
Размещение потока по меткам
Ограничьте ORDERS серверами с обеими метками region:us-east и disk:ssd. CLI принимает отдельный --tag для каждой, библиотеки — список Placement.Tags. --cluster east здесь избыточен, но показывает синтаксис для нескольких кластеров:
- CLI
- C
#!/bin/bash
# Place the ORDERS stream on servers carrying specific tags.
#
# This assumes the 3-node "east" cluster is running with JetStream
# enabled, and that n1-east, n2-east, n3-east each advertise the tags
# region:us-east and disk:ssd via server_tags in their config. See the
# server config block on the placement page for the tag setup.
# Create ORDERS at R=3, constrained to servers carrying BOTH tags.
# --tag is passed once per required tag; the match is an intersection,
# so every listed tag must be present on a server for it to qualify.
# Tag matching folds case (ssd == SSD) but spelling is exact.
#
# --cluster names the cluster every replica must live in. In a single
# cluster like "east" it is a no-op (there is only one cluster), but it
# is shown here so the syntax is familiar when you place across clusters
# later. The match is an intersection of cluster AND tags.
nats --server nats://127.0.0.1:4222 stream add ORDERS \
--subjects "orders.>" \
--replicas 3 \
--cluster east \
--tag region:us-east \
--tag disk:ssd \
--defaults
# If ORDERS already exists, change its placement instead of recreating
# it. The same flags apply on edit; the meta leader re-assigns the
# replicas to servers matching the new constraint.
#
# nats --server nats://127.0.0.1:4222 stream edit ORDERS \
# --cluster east --tag region:us-east --tag disk:ssd
# Read the result. The Cluster block names the leader and the two other
# peers — every one of them is a server you tagged.
nats --server nats://127.0.0.1:4222 stream info ORDERS
# Publish the canonical order to confirm the placed stream accepts
# writes exactly as before — placement changes where, not what.
nats --server nats://127.0.0.1:4222 pub orders.created \
'{"order_id":"ord_8w2k","customer":"acme-co","total_cents":4200,"ts":"2026-05-22T10:14:22Z"}'
// Create ORDERS at R=3, constrained to servers carrying BOTH tags.
// Placement.Tags is a list and the match is an intersection: every
// listed tag must be present on a server for it to qualify. Tag
// matching folds case (ssd == SSD) but spelling is exact.
//
// Placement.Cluster names the cluster every replica must live in.
// In a single cluster like "east" it is a no-op (there is only one
// cluster), but it is shown here so the syntax is familiar when you
// place across clusters later. The match is an intersection of
// cluster AND tags.
jsStreamConfig cfg;
jsPlacement placement;
const char *subjects[] = {"orders.>"};
const char *tags[] = {"region:us-east", "disk:ssd"};
jsPlacement_Init(&placement);
placement.Cluster = "east";
placement.Tags = tags;
placement.TagsLen = 2;
jsStreamConfig_Init(&cfg);
cfg.Name = "ORDERS";
cfg.Subjects = subjects;
cfg.SubjectsLen = 1;
cfg.Replicas = 3;
cfg.Placement = &placement;
s = js_AddStream(&si, js, &cfg, NULL, &jerr);
if (jerr == JSStreamNameExistErr)
{
// ORDERS already exists: change its placement instead of
// recreating it. The same config applies on update; the meta
// leader re-assigns the replicas to servers matching the new
// constraint.
s = js_UpdateStream(&si, js, &cfg, NULL, &jerr);
}
// Read the result. The Cluster block names the leader and the two
// other peers — every one of them is a server you tagged.
if ((s == NATS_OK) && (si->Cluster != NULL))
{
printf("Cluster: %s, leader: %s\n",
si->Cluster->Name, si->Cluster->Leader);
for (i = 0; i < si->Cluster->ReplicasLen; i++)
printf("Replica: %s\n", si->Cluster->Replicas[i]->Name);
}
// Publish the canonical order to confirm the placed stream accepts
// writes exactly as before — placement changes where, not what.
if (s == NATS_OK)
s = natsConnection_PublishString(conn, "orders.created",
"{\"order_id\":\"ord_8w2k\",\"customer\":\"acme-co\","
"\"total_cents\":4200,\"ts\":\"2026-05-22T10:14:22Z\"}");
Лидер метаданных выберет три сервера с обеими метками. В Cluster вывода nats stream info ORDERS лидер и две реплики должны находиться на помеченных узлах.
Несколько меток означают пересечение
Сервер подходит только при наличии каждой метки: region:us-east и disk:ssd.
Регистр не учитывается: disk:ssd, disk:SSD, disk:Ssd эквивалентны. Но написание должно совпадать: disk:sdd не подойдёт. Если метки нет, пересечение пусто, и лидер метаданных отклоняет создание. Ошибка указывает отсутствующую метку в скобках:
nats: error: could not create Stream: no suitable peers for placement, tags not matched ['disk:sdd'] (10005)
Та же ошибка возникает при запросе трёх реплик, если подходящих серверов только два. Условия не ослабляются автоматически.
Все настройки размещения и меток приведены в справочнике. Здесь нужны ограничение кластера и пересечение меток.
Запрос лидерства выбранному серверу
Размещение выбирает держателей реплик, но не лидера. Начального лидера определяет слой метаданных. Поля с его именем нет: preferred в размещении отклоняется с preferred server not permitted in placement. Библиотеки тоже предоставляют в Placement лишь кластер и метки.
После запуска группы можно попросить текущего лидера передать роль определённому участнику через stepdown с предпочтительной целью:
nats stream cluster step-down ORDERS --preferred n2-east
Группа запускает выборы, стараясь назначить n2-east. Это запрос, не закрепление: итог определяет кворум. Проверьте nats stream info ORDERS. Для --preferred нужен NATS Server 2.11 или новее; синтаксис приведён в справочнике.
Типичные ошибки
Обе распространённые ошибки возникают из ожидания более мягких правил размещения.
Отсутствующая метка обнуляет пересечение. Вместо произвольного сервера будет no suitable peers for placement. Регистр ssd и SSD равнозначен, но опечатка sdd — другая метка. Сначала прочитайте фактические метки серверов, затем задавайте условия.
Проверьте наличие меток и результат размещения:
- CLI
- C
#!/bin/bash
# Verify server tags BEFORE placing a stream, then place against exactly
# what the servers advertise — so a typo fails loudly instead of silently
# placing nowhere.
#
# This assumes the 3-node "east" cluster is running with JetStream
# enabled. Tag matching folds case (ssd == SSD) but is matched as an exact
# intersection: every requested tag must be present, spelled correctly, on a
# server for it to qualify.
# Read the tags each server actually advertises. Do not assume the config
# took — a typo in server_tags is silent until a placement asks for a tag
# no server carries. The Tags line in the output is the source of truth.
#
# `nats server info` queries the system account ($SYS), so connect with a
# system user. Name the server you want, or the command answers for whichever
# server replies to the $SYS ping first.
nats server info n1-east
nats server info n2-east
nats server info n3-east
# Now place ORDERS against exactly the tags you just read back.
nats --server nats://127.0.0.1:4222 stream add ORDERS \
--subjects "orders.>" \
--replicas 3 \
--tag region:us-east \
--tag disk:ssd \
--defaults
# If a requested tag is misspelled or missing on every server, the
# intersection is empty and the create fails — it does NOT fall back to
# any server. The error names the tag no server carried, in brackets:
#
# nats: error: could not create Stream: no suitable peers for placement, tags not matched ['disk:sdd'] (10005)
#
# Fix the spelling to match what the servers advertise (case does not
# matter) and re-run. Confirm the placement landed where you intended:
nats --server nats://127.0.0.1:4222 stream info ORDERS
// Read the tags each server actually advertises. Do not assume the
// config took — a typo in server_tags is silent until a placement
// asks for a tag no server carries. There is no dedicated client
// API for this: it is a plain request on the system account's
// $SYS.REQ.SERVER.PING.VARZ subject, filtered by server name. The
// "tags" field of the reply is the source of truth.
const char *names[] = {"n1-east", "n2-east", "n3-east"};
for (i = 0; (s == NATS_OK) && (i < 3); i++)
{
natsMsg *reply = NULL;
char req[64];
snprintf(req, sizeof(req), "{\"server_name\":\"%s\"}", names[i]);
s = natsConnection_RequestString(&reply, sysConn,
"$SYS.REQ.SERVER.PING.VARZ", req, 2000);
if (s == NATS_OK)
{
// Print just the "tags" list out of the VARZ reply.
const char *tags = strstr(natsMsg_GetData(reply), "\"tags\":");
const char *end = (tags != NULL) ? strchr(tags, ']') : NULL;
if (end != NULL)
printf("%s %.*s]\n", names[i], (int)(end - tags), tags);
natsMsg_Destroy(reply);
}
}
// Now place ORDERS against exactly the tags you just read back.
// If a requested tag is misspelled or missing on every server, the
// intersection is empty and the create fails — it does NOT fall
// back to any server. The error names the tag no server carried:
//
// no suitable peers for placement, tags not matched ['disk:sdd']
// (error code 10005)
if (s == NATS_OK)
{
jsStreamConfig cfg;
jsPlacement placement;
const char *subjects[] = {"orders.>"};
const char *tags[] = {"region:us-east", "disk:ssd"};
jsPlacement_Init(&placement);
placement.Tags = tags;
placement.TagsLen = 2;
jsStreamConfig_Init(&cfg);
cfg.Name = "ORDERS";
cfg.Subjects = subjects;
cfg.SubjectsLen = 1;
cfg.Replicas = 3;
cfg.Placement = &placement;
s = js_AddStream(&si, js, &cfg, NULL, &jerr);
if (jerr == JSStreamNameExistErr)
s = js_UpdateStream(&si, js, &cfg, NULL, &jerr);
}
// Confirm the placement landed where you intended: the leader and
// both replicas are servers that advertised the tags.
if ((s == NATS_OK) && (si->Cluster != NULL))
{
printf("Leader: %s\n", si->Cluster->Leader);
for (i = 0; i < si->Cluster->ReplicasLen; i++)
printf("Replica: %s\n", si->Cluster->Replicas[i]->Name);
}
Назначить лидера при размещении нельзя. Размещение ограничивает набор реплик; preferred отклоняется. Не стройте эксплуатацию на предположении «лидер всегда n1-east»: после отказа его выберет кворум. Для запроса роли на определённом сервере используйте nats stream cluster step-down --preferred <server> (см. RAFT и лидеры),
затем проверьте nats stream info: выборы могут не выполнить пожелание.
Что уже готово
Вы пометили n1-east, n2-east, n3-east и ограничили ORDERS сочетанием region:us-east и disk:ssd. Условия образуют пересечение без учёта регистра; отсутствующая или ошибочная метка даёт no suitable peers for placement. Лидер задаётся не размещением, а запрашивается после создания через stepdown.
Кластер всё ещё состоит из трёх серверов: число участников не менялось.
Что дальше
Следующая страница меняет состав: увеличивает число реплик, наблюдает синхронизацию нового участника и безопасно убирает реплику с сервера без потери большинства для записи ORDERS.
Перейдите к масштабированию и управлению участниками.
См. также
- Справочник → Метки сервера — параметры меток и размещения.
- Справочник → API метаданных — назначения лидера метаданных.
- Суперкластеры — географическая привязка между кластерами.