Every test passed. CI was green on every push. And the service I had just deployed was ingesting nothing at all.

Not "ingesting slowly" or "ingesting with errors" — the worker connected to nothing, stored nothing, and logged cheerfully the entire time. The bug had been present in every commit for months.

This is a write-up of the three failures that only appeared once the code left my machine, what each one taught me, and the one design decision that turned out to hold up under real conditions.

What the system does

feedstream ingests live AIS maritime data — ship positions, headings, and voyage information broadcast over WebSocket — stores it idempotently in Postgres, and serves filtered, cursor-paginated queries through a Redis-cached API.

AIS WebSocket ──> worker ──> Postgres │ │ └──> cache invalidation │ client ──> FastAPI ──> Postgres + Redis │ └──> Prometheus ──> Grafana 

The interesting part was never reading a stream and writing rows. It was behaving correctly when the world got messy.

Failure 1: The handshake was slower than the default timeout

The symptom was subtle: /healthz returned 200, the deploy was green, and the events table stayed empty.

The cause was a single default value. websockets.connect has an open_timeout of 10 seconds. Against this particular upstream, the TLS + WebSocket handshake consistently took 19–31 seconds. I measured it three times: 29.9s, 19.0s, 31.0s.

So every connection attempt died during the handshake. Worse, the retry policy only treated dropped connections as retryable:

@tenacity.retry( stop=tenacity.stop_after_attempt(10), wait=tenacity.wait_random_exponential(multiplier=1, max=60), retry=tenacity.retry_if_exception_type(ConnectionClosed), # timeouts not included reraise=True, ) async def _connect_and_consume_with_retry() -> None: await _connect_and_consume() 

A TimeoutError is not a ConnectionClosed, so it skipped the retry wrapper entirely and fell straight out to the outer loop — which logged an error, slept 10 seconds, and tried again forever.

Three fixes went in together.

First, make the timeout explicit and configurable instead of inheriting a library default that was tuned for a different network:

async def connect_func(): # The upstream handshake regularly takes 20-30s, well past the # websockets default of 10s, so the timeout must be configurable. return await websockets.connect( AIS_WS_URL, open_timeout=settings.ais_open_timeout_seconds, # default 60 ) 

Second, treat handshake timeouts as transient, because they are:

retry = (tenacity.retry_if_exception_type((ConnectionClosed, OSError)),) 

Third — and this one was a genuine design bug — the circuit breaker never saw any of these failures. It wrapped a callable that returned a coroutine:

def connect_func(): return websockets.connect(AIS_WS_URL) ws = ais_circuit_breaker.call(connect_func) # returns a coroutine: never raises 

The breaker marked every attempt as a success, because creating a coroutine object cannot fail. The connect failure happened later, when the coroutine was awaited, well outside the breaker's try block. It now exposes an async entry point:

ws = await ais_circuit_breaker.acall(connect_func) 

The lesson: defaults are environmental assumptions. A 10-second timeout is a statement about network conditions, and if you haven't checked it against your network, you haven't tested your client.

Failure 2: A dead cache throttled ingestion 120x

The second discovery was that the ingestion loop was writing so slowly it looked broken. It was: roughly one event every few seconds.

The worker invalidates cached query results after each insert, so readers don't see stale data. That's a reasonable design — until the cache is unreachable. With no timeout configured, each invalidation waited about 2 seconds to fail, and that wait sat directly in the insert path:

if cast(CursorResult, result).rowcount > 0: redis_client_instance = await get_redis_client() await redis_client_instance.delete_pattern("events:*") # 2s when Redis is down 

A cache is supposed to be optional. Here it had become a synchronous dependency of the write path, and its failure mode was the slowest possible one.

The fix has two parts. Bound the failure, then stop paying for it repeatedly:

async def delete_pattern(self, pattern: str) -> int: if self._is_unavailable(): return 0 client = await self.connect() try: deleted = 0 async for key in client.scan_iter(match=pattern, count=500): deleted += int(await client.delete(key) or 0) if deleted: observe_cache_invalidation(deleted) return deleted except redis.RedisError: self._mark_unavailable() # skip Redis entirely for a cooldown return 0 

The client now uses a 1-second connect/command timeout, and after one failure it bypasses Redis for 30 seconds instead of paying the timeout on every single write.

Measured over the same 75-second window, with Redis deliberately unreachable:

Events stored
Before 28
After 3,436

That's roughly 120x, and it's the difference between a service that degrades and a service that stops.

I also replaced KEYS with SCAN in that path. KEYS blocks the Redis event loop while it walks the entire keyspace, which is exactly the wrong thing to do in the middle of an outage.

The lesson: every dependency needs a stated failure mode, and "slow" is usually worse than "down". A dependency that fails fast can be worked around; one that hangs silently takes your whole pipeline with it.

Failure 3: The rate limiter was blocking the event loop

With ingestion fixed, the API started misbehaving under load: /healthz took 5–10 seconds to return, and it returned 200. Not erroring — just crawling.

The cause was that slowapi's Redis storage uses a synchronous client. That client runs inside the async event loop, so every rate-limit check blocked every request. A cache round-trip that should be sub-millisecond was holding the loop hostage.

Two changes:

limiter = Limiter( key_func=get_identifier, storage_uri=_rate_limit_storage_uri(settings.redis_url), in_memory_fallback_enabled=True, swallow_errors=True, # limits' Redis client is synchronous and runs on the event loop, # so an unreachable Redis would stall every request. Bound it hard. storage_options={"socket_connect_timeout": 1, "socket_timeout": 1}, ) 

Bounded timeouts keep the worst case short. And on a single-instance deployment, RATE_LIMIT_STORAGE_URI=memory:// uses in-process counters — which are more accurate than shared storage when there is only one process, and involve no network call at all.

/healthz went from 5–10 seconds to 96 ms.

The lesson: "async" is a property of your code, not your dependency graph. One synchronous client anywhere in a request path can serialize your entire service.

The decision that held: dedup lives in the database

The bugs above were all fixable. The part I'd defend in review is the one that never broke.

AIS feeds replay events constantly. Reconnections are routine, and after any disconnect you receive messages you've already seen. If inserts are naive, duplicates accumulate quietly and corrupt every downstream aggregate.

The tempting fix is application-level: keep a set of seen IDs, or a Redis window. Both work until the process restarts, or the key expires, or two workers disagree about what they've seen.

Instead, each event gets a deterministic key, and the database enforces it:

message_type = data.get("MessageType", "unknown") mmsi = str(data.get("MetaData", {}).get("MMSI", "")) time_utc = data.get("MetaData", {}).get("time_utc", "") dedup_key = f"{mmsi}:{message_type}:{time_utc}" 
stmt = insert(Event).values(**event_dict).on_conflict_do_nothing(index_elements=["dedup_key"]) result = await session.execute(stmt) if cast(CursorResult, result).rowcount > 0: return "inserted" return "duplicate" 

This has a useful property: correctness does not depend on the worker being careful. It survives restarts, deploys, and replayed backlogs, because the rule lives in the schema. The insert either happens or it doesn't.

After ingesting 115,000+ events from the live feed, the count of rows equals the count of distinct dedup_key values. Zero duplicates — not by discipline, but by construction.

It also made the metrics honest. inserted versus duplicate is a real counter, not an inference, so replay behaviour is visible in Prometheus rather than guessed at.

Verifying with observability rather than optimism

None of the three failures were visible from unit tests. All three were visible within a minute of watching a dashboard.

Here's the stack during a local run, ingesting live data:

Feedstream Grafana dashboard: ingestion rate, ingestion and query p95 latency, worker state, cache hit ratio, DB pool usage

What each panel actually caught:

  • Events Ingested / sec — flat at zero is what exposed failure 1.
  • Worker State — a one-hot gauge (connected / retrying / disconnected) that made the retry loop obvious.
  • Ingestion p95 latency — ~4.9 ms, confirming the write path was healthy once the cache was no longer in it.
  • Query p95 latency — ~9 ms after the first cold query.
  • Cache hit ratio — showed invalidation working (and its absence during the outage).
  • DB pool usage — would have caught connection exhaustion before it became an incident.

The follow-on insight was that my counters had to distinguish rejected, duplicate, and inserted. A single "events processed" counter would have hidden failure 1 completely: the worker was processing plenty of events. It just wasn't storing any.

What I'd do differently

  • Test the network assumptions, not just the code. A single integration test that opens the real socket and asserts it receives one message would have caught failure 1 before deploy.
  • Give every external client an explicit timeout. Not one inherited from a library, not "the default" — a number I chose and can justify.
  • Decide each dependency's failure mode up front. Cache: degrade to Postgres. Rate limiter: allow. Upstream: back off. "Whatever happens" is not a failure mode.
  • Put correctness in the schema when you can. Application-level guarantees evaporate on restart.

The honest caveat

It runs on a free tier, so the instance sleeps after 15 minutes without traffic and the first request afterwards takes about a minute to wake. CI gates every push, and deploys only run after CI passes.

Everything else is real: live data, real migrations, real metrics — and three bugs I'd never have found by reading the code.

Links

If you've hit a failure that only shows up in production, I'd like to hear which one — the timeout-shaped ones are the hardest to see.