Skip to content

FX-047: keep events on temporary errors, honour Retry-After, count drops, bound flush() - #3

Merged
czypnt merged 4 commits into
mainfrom
fx-047-keep-events-on-temporary-errors
Nov 22, 2026
Merged

czypnt merged 4 commits into
mainfrom
fx-047-keep-events-on-temporary-errors

Conversation

@czypnt

@czypnt czypnt commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

What was wrong

The SDK deleted events during a server outage. In 1.3.4 a temporary failure (5xx, 503, 429, 408, a timeout or a network error) got retryLimit quick retries, then went back to the queue; _flush() counted failed flush cycles per event and, at MAX_FLUSH_ATTEMPTS = 10, called onDrop(..., 'max_flush_attempts') and threw the event away. With the 10 s flush timer that is about two minutes, so a two-minute outage lost events for good. Also:

  • Retry-After was never read.
  • The queue cap dropped the oldest events with one warning the first time and no count.
  • flush() had no time bound.

What the ingest worker answers on POST /track

Taken from infra/cloudflare/ingest/index.js handleServerTrack on monorepo main ef756fd42, and pinned by infra/cloudflare/tests/ingest-answer-contract.test.js:

Answer Meaning SDK now
200 (stored, or a duplicate eventId) done never sent again
400, 405, 413, 415 malformed, no event name or identity, wrong method, too large final: dropped as permanent_client_error
401 no key, over-long key, or a key a healthy lookup refused. Its own database failure answers 503 because INGEST_OWN_FAULT_503 = "on" in production. final: dropped as auth_refused (new reason), as in 1.3.4
429 + Retry-After: 1 rate limited kept, waits out Retry-After
500 queue outage or unexpected error; the dedup claim is released, so the retry is not treated as a duplicate kept, backoff
503 + Retry-After: 5 the server's own fault kept, waits out Retry-After

The server deduplicates on eventId for 7 days, so retrying with the same id is safe.

What changes

  • A temporary failure keeps the event. It is retried with backoff (1 s, 2 s, 4 s and so on, up to 60 s between cycles, jittered) for maxRetryDuration, a new option that defaults to 1 hour (allowed range 1 minute to 24 hours). After that it is dropped as max_flush_attempts; the name is kept.
  • Retry-After is honoured, as seconds or as an HTTP date, capped at 5 minutes, plus up to 20% jitter so clients do not all retry at the same instant. A malformed value is ignored. A short one is waited out inside the quick retries. One over 10 s sends the event back to the queue, which does not send it before that time.
  • 401/403 are final, as in 1.3.4. They are counted under the new drop reason auth_refused, with the loud authentication line once and in the summary line.
  • maxQueueSize now bounds queued plus in-flight events, including re-queued failures, so memory stays bounded through an outage. The queue stays in arrival order. The oldest queued event is evicted as queue_overflow and counted. When every held event is in flight, the new one is dropped.
  • Every retry sends the same event object, so the eventId is the same. The event id builder is untouched; only its doc comment now says 7-day window instead of 6h.
  • getStats() (new) returns { queued, inFlight, dropped, droppedByReason }. Every drop is counted. Drops from the cap, final answers, auth refusals and expired retries are logged as one summary line per flush cycle, never per event.
  • flush() waits at most flushTimeout, a new option that defaults to 30 s. flush() and close() resolve with { unsent } and log one line when it is above zero. close() waits out backoff and Retry-After within closeTimeout and never sends early.

How it was tested

The tests were written first; each failed on the earlier code and passes now. tests/retry.ts mocks fetch and moves Date.now forward. It covers:

  • a 15-minute outage mixing 503, 500, 429, timeout, network error and 502: the event is delivered once, nothing is dropped, every attempt carries the same id, and the event is never re-sent after its 2xx
  • a steady sender through a 30-minute 503 outage with a cap of 100: queued plus in-flight never goes above 100 (the reviewer measured 2,790 before this fix; this test measured 575 before it), and every event is either held or counted as queue_overflow
  • the drop as max_flush_attempts after maxRetryDuration
  • Retry-After as seconds, as an HTTP date, malformed, and long (120 s, not sent early)
  • close() waiting out a 2 s backoff, then delivering
  • 401/403 sent once, dropped as auth_refused, counted, with one summary line; 400/413 final
  • the cap count and its single summary line, and flush()/close() returning inside their bounds with unsent

tests/test.ts keeps every earlier check; the 401 section only expects the new reason name. npm test runs both files. tsc --noEmit and npm run build pass locally on Node 26, and I ran the suite twice. CI runs Node 22 and 24.

What an integrator sees

  • During an outage, events wait in memory, up to maxQueueSize including in-flight events, and arrive when the server recovers.
  • Breaking for typed code: flush() and close() return Promise<FlushResult> ({ unsent }) instead of Promise<void>. Code that ignores the value is unaffected. A subclass overriding flush(): Promise<void>, or code typed to expect Promise<void>, no longer type-checks.
  • 401/403 reach onDrop as auth_refused, not permanent_client_error. max_flush_attempts fires only after maxRetryDuration.
  • Log lines:
    • removed: Queue full (N) — dropping oldest events. ... and Dropping event after N failed flush attempts: <event>
    • added: N event(s) dropped since the last report (<reason>=<n>, ...); getStats() has the totals. (at most once per flush cycle) and flush(): N event(s) not delivered yet; kept in memory and retried later.
    • changed: the close(): N event(s) undelivered ... line now counts in-flight events and ends with : Q queued, F still in flight.

Known limits

Events still in memory when a process exits or a serverless function is frozen are lost without being counted. During a 503 outage a flush can wait 15 to 20 seconds, where 1.3.4 waited 4 to 7.

Release

This ships as a minor release, 1.4.0, because the return type of flush() and close() changed. The version is not bumped; the changelog entry stays under Unreleased. Publishing is a separate decision. Nothing is needed on the server first.

🤖 Generated with Claude Code

czypnt and others added 3 commits November 21, 2026 12:13
…ops, bound flush()

- 5xx/503/429/408/timeout/network: the event is kept and retried with backoff
  (up to 60 s between cycles) for maxRetryDuration (default 1 h) instead of being
  deleted after 10 failed flush cycles (~2 minutes). Same event object, same eventId.
- Retry-After (seconds or HTTP date, capped at 5 min) is honoured inline and between cycles.
- 401/403 kept and retried for 10 minutes, then dropped; other 4xx stay final.
- getStats(): queued, in-flight and dropped counts by reason; drops logged as one
  summary line per flush cycle.
- flush() bounded by flushTimeout (default 30 s); flush() and close() resolve with { unsent }.
- Event id builder unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…03 final, jitter on Retry-After

- maxQueueSize now bounds queued + in flight; a re-queued failure counts against it and
  the oldest queued event is evicted as queue_overflow (counted). Queue kept in arrival order.
- 401/403 are final again (the server answers 503 for its own faults), counted as the new
  drop reason auth_refused and in the summary line.
- Retry-After waits get up to 20% jitter, between cycles and in the quick retries.
- Tests: steady sender through a 30-minute outage never exceeds the cap; drop after
  maxRetryDuration; malformed Retry-After; close() waits out a backoff.
- eventId doc comment: 7-day dedup window. Changelog: ships as 1.4.0 (flush/close return type).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts resolved only: src/index.ts keeps this PR's code exactly (comment-stripped
compare identical) with internal ticket ids removed from comments, as on main;
README.md takes main's new short README (the full reference lives on the docs site).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@czypnt
czypnt merged commit 0775d61 into main Nov 22, 2026
2 checks passed
@czypnt
czypnt deleted the fx-047-keep-events-on-temporary-errors branch November 22, 2026 23:38
czypnt added a commit that referenced this pull request Nov 22, 2026
Source resolutions:
- src/index.ts TrackOptions.externalIds JSDoc: this PR's rewrite.
- src/index.ts fields: main's retry/inFlight/drop-count fields kept; this PR's
  warnedKinds, exitFlushed and shared liveClients/exitListener kept; flushAttempts
  (gone in main) and exitHook (gone here) dropped.
- src/index.ts registerExitHook: this PR's shared beforeExit listener, calling
  main's startDrain() instead of flush(), as main's per-client hook did.
- src/index.ts _flush failure path: main's handleFailure; this PR's once-only
  "failed flush attempts" warning dropped in favour of main's per-cycle drop summary.
- tests/test.ts W3: the 10-cycle drop no longer exists; now two final-400 drops in
  one flush must give one summary line. W14 network-recovery test waits out the
  first backoff before re-flushing.
- CHANGELOG: one Unreleased; this PR's entries under main's Changed/Added, the
  warning entry no longer mentions failed-attempt drops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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