Skip to content

feat(transport): one retry rule across the SDKs - #8

Merged
zaytcevcom merged 2 commits into
mainfrom
chore/align-retry-predicates
Sep 17, 2026
Merged

zaytcevcom merged 2 commits into
mainfrom
chore/align-retry-predicates

Conversation

@zaytcevcom

Copy link
Copy Markdown
Contributor

Решение

Единое правило во всех трёх SDK — «транзиентно, пока не доказано обратное»:

нет ответа вообще → повторять
408 → повторять
429 → повторять
501 → НЕ повторять          ← единственный вырез
>= 500 → повторять
всё остальное → НЕ повторять

Почему общее правило, а не аллоу-лист

Довод за аллоу-лист («не даст молча отретраить то, что ретраить не следует») не выживает при встрече с этим бэкендом. Он отображает любое неожиданное состояние в 500 — включая дедлайн таймаут-мидлвари и панику в хендлере. То есть по-настоящему безнадёжный отказ и так приходит как 500, который аллоу-лист послушно ретраит. Защиты он не даёт ни на одном коде, где риск реален; его единственный фактический эффект — выбрасывать коды, которым его не научили.

Дальше решает асимметрия цен:

  • аллоу-лист ошибся на незнакомом транзиентном 5xx → событие потеряно молча и навсегда, а это единственный отказ, которого у трекера ошибок быть не должно;
  • общее правило ошиблось на незнакомом терминальном 5xx → ограниченное число лишних запросов, ошибка всё равно доезжает до потребителя, дубля нет: eventId — ключ идемпотентности.

И главное: предикат судит статусы, которые SDK не контролирует. Инсталляция стоит за чужим edge, а сам SDK живёт запиненной зависимостью в чужом дереве — расширять аллоу-лист пришлось бы релизом в каждый проект-потребитель.

Почему 408 ретраится

408 реально достижим: у nginx на /api/ не выставлены таймауты на приём тела, работает дефолт 60 с. Это edge, у которого истекло терпение на приёме, — высказывание о канале, а не о payload. RFC 9110 §15.5.9 прямо разрешает повторить такой запрос без изменений.

Что изменится у потребителя

Статус Go PHP JS
408 1 попытка → MaxRetries+1 1 → 3 без изменений
прочие 5xx (505, 507, 520–527, 599, будущие) без изменений без изменений 1 → 3
429, 500, 502, 503, 504 без изменений без изменений без изменений
501 терминален терминален терминален (теперь явно)
attempts в отчёте об отказе правда правда теперь правда

Самое существенное — в JS. События, упиравшиеся в 5xx вне {500,502,503,504}, терялись молча после одной попытки: у кого инсталляция за Cloudflare с его 520–527, те события просто исчезали. И attempts сообщал сконфигурированный бюджет вместо реального числа попыток, то есть метрики на нём врали.

В Go по умолчанию MaxRetries = 0, так что без явного включения ретраев не меняется ничего.

В PHP 408 теперь стоит до двух лишних синхронных вызовов и ~300 мс в запросном пути — реальная цена, взамен событие переживает таймаут edge.

Доказательство, что свели

Прогнаны реальные реализации всех трёх по каждому статусу 200–599 плюс «ответа не было», дампы сравнены: diff чист, три файла идентичны.

Осознанные различия — названы в комментариях

  1. Как выглядит «нет ответа»: в Go ошибка от http.Client.Do; в PHP ненулевой curl_errno при статусе 0; в JS отклонённый промис fetch, где статуса нет вообще и выразить его в предикате нельзя. Все трое ретраят.
  2. Бюджет ретраев: в Go они opt-in, потому что транспорт может работать прямо в запросном пути вызывающего; в PHP и JS дефолт 2. Решение общее, бюджет — нет.
  3. 409 в JS не доходит до предиката: он считается успехом. Go и PHP приходят к тому же ответу другим путём.

Ловушка для следующего

В комментарии рядом с вырезом закреплено: вырез на 501 нельзя распространять на 503. После duckbug#489 «не сконфигурировано» переедет на 501, но на ingest-роутах 503 — это edge во время раскатки, и ретраить его правильно.

Отдельно, не чинилось здесь

Предикат успеха разъехался на троих: PHP считает дубликат (409) отказом и дёргает обработчик ошибки на каждое дублирующееся событие, Go ставит флаг, JS считает успехом. На ретраи не влияет — отдельное решение.

🤖 Generated with Claude Code

The three SDKs disagreed about retrying, in behaviour and not only in
shape. JS listed the statuses it would retry; Go and PHP retried any 5xx
but 501. So 408 retried in JS and not in Go or PHP, and an unfamiliar 5xx
retried in Go and PHP and not in JS.

All three now read: no response at all, 408, 429, or 5xx other than 501.

The allow-list argument — that it cannot silently retry what should not be
retried — does not survive this backend. Every unexpected state maps to 500
there, including the request timeout middleware and a panic in a handler.
So the genuinely hopeless failure already arrives as a 500 that the list
happily retries; the list protects nothing where the risk is real, and only
drops codes nobody taught it.

What decides it is the asymmetry. A list wrong about an unfamiliar
transient 5xx loses the event silently and for good, which is the one
failure an error tracker must not have. A general rule wrong about an
unfamiliar terminal 5xx costs a bounded number of requests and still
surfaces the error; eventId is the idempotency key, so no duplicate.

And the predicate judges statuses the SDK does not control: an installation
sits behind somebody else's edge, and the SDK sits pinned in somebody else's
tree. Widening a list would take a release into every consumer.

408 retries because it is reachable: nginx has no client body timeout set on
/api/, so the default 60s applies. It is the edge losing patience with the
upload, a statement about the channel rather than the payload, and RFC 9110
permits repeating it unchanged.

Differences that remain are named in each comment rather than left to be
inferred: what "no response" looks like in each runtime, and that the retry
budget is opt-in in Go because its transport can run in the caller's request
path.

BREAKING CHANGE: none, but TransportFailureInfo.attempts now reports the
attempts actually made rather than the configured budget, so metrics built
on that number will move.
…sts on

The README said every other 4xx, 409 included, is reported to the caller.
The opposite is true: 409 sets Duplicate, IsSuccess() returns true, and
handleTransportResult returns before it ever builds FailureInfo, so the
transport failure handler is not called at all.

The retry predicate is now identical across the three SDKs; what a duplicate
looks like afterwards is not, and that is worth stating rather than leaving
to be discovered. JS also folds 409 into success; PHP hands it to its failure
handler because its isSuccess() requires 2xx.

The claim that a retry cannot create a second event was stronger than the
truth. Ingest deduplicates on a Postgres primary key with ON CONFLICT DO
NOTHING, with no expiry, on the single and the batch route alike — but only
if the caller supplies the id. A payload that reaches ingest without an
eventId gets a fresh one minted per request, so a retry does store it twice.
All three SDKs generate a UUIDv4 on the normal path; the guarantee is now
written with its condition instead of without it.

The transport-error branch of shouldRetry had no test. It has one now, with
a handler that hijacks the connection and closes it unanswered, and it was
proven to bite by deleting the branch and watching the case fail.
@zaytcevcom
zaytcevcom merged commit deb10f3 into main Sep 17, 2026
1 check passed
@zaytcevcom
zaytcevcom deleted the chore/align-retry-predicates branch September 17, 2026 05:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant