Repository navigation
Stop losing ingest: reconnect forever, persist the cursor, never drop a batch - #13
Merged
Merged
Conversation
… 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>
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.
Why
About 1–1.5% of all Bluesky posts never get ingested. Production evidence (2026-10-29):
run_streamcaught onlyConnectionClosedError. A refused handshake (503/429), a socket error or a timeout escaped and killed the process. A clean close (ConnectionClosedOK) quietly ended the iterator, sorun_from_jetstreamreturned and the process exited.MultipleEgresslogged egress exceptions and swallowed them, andSQSEgressignored theFailedlist returned bySendMessageBatch._process_batchdidawait asyncio.create_task(...), so hydration ran one batch at a time andSemaphore(100)never had more than one holder. Bursts at :00 and :30 fell behind.Changes
Reconnect forever (
client.py)InvalidStatus/InvalidMessage),OSError,TimeoutError,ConnectionClosedOK/ConnectionClosedError, and any otherException. A socket that stays open but delivers nothing for 60s is also treated as dead. Cancellation still stops the stream.JetstreamClientnow takes the whole host list. It starts on a random host and moves to the next host on every reconnect. Before,random.choicepicked one host once.time_usseen, minus a 2s margin. Jetstream hosts don't share a clock, and duplicates are deduped downstream. Gaps are not.max_retries/retry_windowlogic, which logged "Ending" but never ended.Persisted cursor (new
cursor.py,turbocharger.py)CursorTrackerkeeps a low-water mark: the oldest starttime_usof any batch not yet egressed, or the newest egressedtime_uswhen 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.CURSOR_REDIS_URLis set,CursorStorewrites the mark to Redis at most once per second, using the sameredis.asyncioclient asRedisEgress. 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.--modulo, the key is suffixed with:{shard}/{modulo}, so each shard keeps its own cursor.Concurrent hydration (
turbocharger.py)_process_batchacquires the semaphore, starts the task, keeps a reference to it in_in_flight, and returns without waiting.HYDRATION_CONCURRENCY(default 16).drain()waits for in-flight batches when the stream ends.No dropped batches (
turbocharger.py,hydration.py)Hydration.unhydrated_bulk. That output has exactly the shapehydrate_bulkproduces when every lookup comes back empty:user/parent_post/reply_post/quote_postareNoneand mentions map toNone. A test asserts that equality.hydrate_bulkwas refactored into_collect_referencesand_assembleso both paths share one implementation. Its behaviour is unchanged, and the existing tests still pass.Egress that does not lie (
egress/)SQSEgress:Failedentries, 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 raisesEgressError.SenderFault, since they would fail the same way forever. They are logged at error level and counted asrejected.SQS_MAX_BATCH_BYTESin total. If SQS still returnsBatchRequestTooLong, it halves the request and resends.MultipleEgressretries 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, incrementsegress_failures_total{reason="exhausted"}and raisesEgressError. 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}, wherereasonis one of handshake, closed_ok, closed_error, idle, timeout, os_error, otherjetstream_turbo_hydration_retries_totaljetstream_turbo_unhydrated_records_totaljetstream_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 replayNew settings (env, all optional)
CURSOR_REDIS_URLCURSOR_KEYjetstream_turbo:cursor:{shard}/{modulo}when shardedCURSOR_MAX_AGE_SECONDS1800CURSOR_FLUSH_INTERVAL_SECONDS1.0CURSOR_RESUME_MARGIN_SECONDS2.0RECONNECT_MAX_BACKOFF_SECONDS30JETSTREAM_IDLE_TIMEOUT_SECONDS60HYDRATION_CONCURRENCY16HYDRATION_ATTEMPTS3EGRESS_ATTEMPTS4SQS_MAX_BATCH_BYTES262144Rollout
CURSOR_REDIS_URLis set. Set it in the deployment env as part of this deploy. Any Redis/Valkey reachable from the pod works, including the one behindREDIS_URL. Without it, everything else in this PR still applies, but restarts keep live-tailing.No persisted jetstream cursor ... STARTING FROM THE LIVE TAILonce. Every restart after that resumes from the stored cursor, as long as it is younger than 30 minutes.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_totalby reason.jetstream_turbo_unhydrated_records_total.Tests
37 tests pass (
pytest): 4 existing and 33 new. All use fakes, with no network.ConnectionClosedOK,ConnectionClosedError,OSError,TimeoutErrorand an idle socket, checking host rotation, the cursor margin and the reconnect metric.Failedentries retried and only those, exhaustion raising, sender faults not retried, size-based packing, the 10-entry cap, oversized records sent unhydrated, andBatchRequestTooLongsplitting.MultipleEgressretrying 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