Repository navigation
feat(transport): one retry rule across the SDKs - #8
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Решение
Единое правило во всех трёх SDK — «транзиентно, пока не доказано обратное»:
Почему общее правило, а не аллоу-лист
Довод за аллоу-лист («не даст молча отретраить то, что ретраить не следует») не выживает при встрече с этим бэкендом. Он отображает любое неожиданное состояние в 500 — включая дедлайн таймаут-мидлвари и панику в хендлере. То есть по-настоящему безнадёжный отказ и так приходит как 500, который аллоу-лист послушно ретраит. Защиты он не даёт ни на одном коде, где риск реален; его единственный фактический эффект — выбрасывать коды, которым его не научили.
Дальше решает асимметрия цен:
eventId— ключ идемпотентности.И главное: предикат судит статусы, которые SDK не контролирует. Инсталляция стоит за чужим edge, а сам SDK живёт запиненной зависимостью в чужом дереве — расширять аллоу-лист пришлось бы релизом в каждый проект-потребитель.
Почему 408 ретраится
408 реально достижим: у nginx на
/api/не выставлены таймауты на приём тела, работает дефолт 60 с. Это edge, у которого истекло терпение на приёме, — высказывание о канале, а не о payload. RFC 9110 §15.5.9 прямо разрешает повторить такой запрос без изменений.Что изменится у потребителя
MaxRetries+1attemptsв отчёте об отказеСамое существенное — в JS. События, упиравшиеся в 5xx вне
{500,502,503,504}, терялись молча после одной попытки: у кого инсталляция за Cloudflare с его 520–527, те события просто исчезали. Иattemptsсообщал сконфигурированный бюджет вместо реального числа попыток, то есть метрики на нём врали.В Go по умолчанию
MaxRetries = 0, так что без явного включения ретраев не меняется ничего.В PHP 408 теперь стоит до двух лишних синхронных вызовов и ~300 мс в запросном пути — реальная цена, взамен событие переживает таймаут edge.
Доказательство, что свели
Прогнаны реальные реализации всех трёх по каждому статусу 200–599 плюс «ответа не было», дампы сравнены:
diffчист, три файла идентичны.Осознанные различия — названы в комментариях
http.Client.Do; в PHP ненулевойcurl_errnoпри статусе 0; в JS отклонённый промисfetch, где статуса нет вообще и выразить его в предикате нельзя. Все трое ретраят.Ловушка для следующего
В комментарии рядом с вырезом закреплено: вырез на 501 нельзя распространять на 503. После duckbug#489 «не сконфигурировано» переедет на 501, но на ingest-роутах 503 — это edge во время раскатки, и ретраить его правильно.
Отдельно, не чинилось здесь
Предикат успеха разъехался на троих: PHP считает дубликат (409) отказом и дёргает обработчик ошибки на каждое дублирующееся событие, Go ставит флаг, JS считает успехом. На ретраи не влияет — отдельное решение.
🤖 Generated with Claude Code