Skip to content

Stop losing ingest: reconnect forever, persist the cursor, never drop a batch - #13

Merged
DGaffney merged 1 commit into
mainfrom
fix/ingest-loss-resilience
Oct 29, 2026
Merged

DGaffney merged 1 commit into
mainfrom
fix/ingest-loss-resilience

Conversation

@DGaffney

Copy link
Copy Markdown
Contributor

Why

About 1–1.5% of all Bluesky posts never get ingested. Production evidence (2026-10-29):

  • Crashes. The single prod pod exited with code 1 79 times between 10/21 and 10/29 (EKS audit log), about 9 a day. run_stream caught only ConnectionClosedError. A refused handshake (503/429), a socket error or a timeout escaped and killed the process. A clean close (ConnectionClosedOK) quietly ended the iterator, so run_from_jetstream returned and the process exited.
  • Outage. On 10/22, 21:29–22:26 UTC, CrashLoopBackOff turned those exits into a 57-minute ingest outage.
  • Backlog lost on every restart. The cursor lived only in memory, so each restart resumed from the live tail. Everything posted while the pod was down was gone for good.
  • Silent batch drops. Separately, runs of 8–53 consecutive posts vanished within a second, with no crash. We confirmed this by replaying jetstream against the S3 archive. Any hydration exception dropped its whole batch after logging, MultipleEgress logged egress exceptions and swallowed them, and SQSEgress ignored the Failed list returned by SendMessageBatch.
  • Falling behind on bursts. _process_batch did await asyncio.create_task(...), so hydration ran one batch at a time and Semaphore(100) never had more than one holder. Bursts at :00 and :30 fell behind.

Changes

Reconnect forever (client.py)

  • Every connection failure now reconnects: handshake errors (InvalidStatus/InvalidMessage), OSError, TimeoutError, ConnectionClosedOK/ConnectionClosedError, and any other Exception. A socket that stays open but delivers nothing for 60s is also treated as dead. Cancellation still stops the stream.
  • Backoff is exponential with jitter, capped at 30s, and resets after any connection that delivered messages.
  • JetstreamClient now takes the whole host list. It starts on a random host and moves to the next host on every reconnect. Before, random.choice picked one host once.
  • Every reconnect resumes from the last time_us seen, minus a 2s margin. Jetstream hosts don't share a clock, and duplicates are deduped downstream. Gaps are not.
  • Removed the dead max_retries/retry_window logic, which logged "Ending" but never ended.

Persisted cursor (new cursor.py, turbocharger.py)

  • CursorTracker keeps a low-water mark: the oldest start time_us of any batch not yet egressed, or the newest egressed time_us when nothing is in flight. Batches now finish out of order, so this is the only safe value. A batch whose egress fails for good holds the mark at its start for the rest of the process's life.
  • When CURSOR_REDIS_URL is set, CursorStore writes the mark to Redis at most once per second, using the same redis.asyncio client as RedisEgress. On startup it resumes from the stored cursor if it is younger than 30 minutes. Otherwise it live-tails and logs an error saying so.
  • If Redis is unreachable, the process does not crash. It falls back to the old live-tail behaviour.
  • With --modulo, the key is suffixed with :{shard}/{modulo}, so each shard keeps its own cursor.
  • The cursor is not used in SQS input mode.

Concurrent hydration (turbocharger.py)

  • _process_batch acquires the semaphore, starts the task, keeps a reference to it in _in_flight, and returns without waiting.
  • Concurrency is bounded by HYDRATION_CONCURRENCY (default 16).
  • drain() waits for in-flight batches when the stream ends.
  • SQS input mode still processes batches one at a time, and now marks messages complete only after a successful egress. A failed batch is redelivered by SQS instead of being acknowledged.

No dropped batches (turbocharger.py, hydration.py)

  • Hydration is retried with backoff (3 attempts by default).
  • If every attempt fails, the records are egressed unhydrated via the new Hydration.unhydrated_bulk. That output has exactly the shape hydrate_bulk produces when every lookup comes back empty: user/parent_post/reply_post/quote_post are None and mentions map to None. A test asserts that equality.
  • hydrate_bulk was refactored into _collect_references and _assemble so both paths share one implementation. Its behaviour is unchanged, and the existing tests still pass.

Egress that does not lie (egress/)

  • SQSEgress:
    • Retries Failed entries, and only those, with backoff and a bounded number of attempts. It also retries when the whole call fails. If entries are still failing after the last attempt, it raises EgressError.
    • Does not retry entries rejected with SenderFault, since they would fail the same way forever. They are logged at error level and counted as rejected.
    • Packs requests to at most 10 entries and SQS_MAX_BATCH_BYTES in total. If SQS still returns BatchRequestTooLong, it halves the request and resends.
    • A single record too large to fit on its own (hydrated profiles and posts can be big) is sent unhydrated rather than dropped.
  • MultipleEgress retries only the methods that failed, so the ones that succeeded are not re-sent. If a method is still failing after the last attempt, it logs at error with record counts, increments egress_failures_total{reason="exhausted"} and raises EgressError. The turbocharger catches that and holds the cursor, so a restart replays the batch.

Metrics (metrics.py). Every labelled series is created at 0 at import, so alerts can fire on the first occurrence.

  • jetstream_turbo_reconnects_total{reason}, where reason is one of handshake, closed_ok, closed_error, idle, timeout, os_error, other
  • jetstream_turbo_hydration_retries_total
  • jetstream_turbo_unhydrated_records_total
  • jetstream_turbo_egress_retries_total{egress}
  • jetstream_turbo_egress_failures_total{egress,reason}
  • jetstream_turbo_cursor_lag_seconds: now minus the low-water cursor, which is the window a restart would replay

New settings (env, all optional)

Env Default
CURSOR_REDIS_URL unset → cursor persistence disabled Redis to persist the cursor in
CURSOR_KEY jetstream_turbo:cursor Suffixed :{shard}/{modulo} when sharded
CURSOR_MAX_AGE_SECONDS 1800 Older stored cursors are ignored, and the process live-tails
CURSOR_FLUSH_INTERVAL_SECONDS 1.0
CURSOR_RESUME_MARGIN_SECONDS 2.0 Subtracted from the cursor on every resume
RECONNECT_MAX_BACKOFF_SECONDS 30
JETSTREAM_IDLE_TIMEOUT_SECONDS 60
HYDRATION_CONCURRENCY 16 Was effectively 1
HYDRATION_ATTEMPTS 3
EGRESS_ATTEMPTS 4 Applies to each egress method and to SQS entries
SQS_MAX_BATCH_BYTES 262144

Rollout

  • Cursor persistence is off until CURSOR_REDIS_URL is set. Set it in the deployment env as part of this deploy. Any Redis/Valkey reachable from the pod works, including the one behind REDIS_URL. Without it, everything else in this PR still applies, but restarts keep live-tailing.
  • The first deploy still starts from the live tail, because nothing has been persisted yet. It logs No persisted jetstream cursor ... STARTING FROM THE LIVE TAIL once. Every restart after that resumes from the stored cursor, as long as it is younger than 30 minutes.
  • Watch:
    • jetstream_turbo_cursor_lag_seconds, which should sit at a few seconds. If it climbs steadily, a batch failed egress and is holding the cursor.
    • jetstream_turbo_reconnects_total by reason.
    • jetstream_turbo_unhydrated_records_total.
  • Downstream sees more duplicates after reconnects and restarts (the 2s margin, plus replaying in-flight batches) and slightly reordered records, because batches now finish concurrently. Both are expected and deduped by the matcher and ClickHouse.

Tests

37 tests pass (pytest): 4 existing and 33 new. All use fakes, with no network.

  • Reconnect after a 503 handshake, ConnectionClosedOK, ConnectionClosedError, OSError, TimeoutError and an idle socket, checking host rotation, the cursor margin and the reconnect metric.
  • Low-water mark when batches finish out of order, and a failed batch holding it.
  • Hydration failure leading to unhydrated egress (not a drop), and unhydrated output matching an empty hydration exactly.
  • Bounded concurrency.
  • SQS Failed entries retried and only those, exhaustion raising, sender faults not retried, size-based packing, the 10-entry cap, oversized records sent unhydrated, and BatchRequestTooLong splitting.
  • MultipleEgress retrying only the failed method and raising instead of swallowing.

flake8 reports nothing new. Every remaining warning is on lines this PR does not touch. I also ran the client against the real jetstream once by hand: a bad host first, then rotation to a good one, with the resume cursor including the margin.

🤖 Generated with Claude Code

… a batch

The single prod pod exited 1 roughly 9x/day, and every restart resumed
from the live tail because the jetstream cursor lived only in memory.
Separately, any hydration or egress error dropped its batch silently.

- client: reconnect on every connection failure (handshake 503/429,
  socket errors, timeouts, clean close, idle socket) with capped
  jittered backoff, rotating through all configured hosts and resuming
  from the last cursor minus a 2s margin.
- cursor: persist a low-water cursor (only egressed records, never past
  an in-flight or failed batch) to Redis every ~1s when CURSOR_REDIS_URL
  is set; resume from it on startup if younger than 30 minutes.
- turbocharger: batches actually run concurrently (bounded, default 16);
  hydration retries, then egresses unhydrated instead of dropping.
- egress: SQS retries Failed entries, packs batches under the payload
  limit and splits on BatchRequestTooLong; MultipleEgress retries only
  the failing method and raises instead of swallowing.
- metrics: reconnects by reason, hydration retries, unhydrated records,
  egress retries/failures, cursor lag; labelled series exported at 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DGaffney
DGaffney merged commit c82e2a1 into main Oct 29, 2026
1 of 3 checks passed
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