<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sai Charan J on Medium]]></title>
        <description><![CDATA[Stories by Sai Charan J on Medium]]></description>
        <link>https://medium.com/@sai-charan-j?source=rss-1ec656e84339------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D9y2ukFsx_4Kzz3sGHsUOw.png</url>
            <title>Stories by Sai Charan J on Medium</title>
            <link>https://medium.com/@sai-charan-j?source=rss-1ec656e84339------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:21:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sai-charan-j/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spiky In, Steady Out: Building a Throttle-Safe Trace Collector for AI Traces]]></title>
            <link>https://medium.com/@sai-charan-j/spiky-in-steady-out-building-a-throttle-safe-trace-collector-for-ai-traces-c745b4a90f1f?source=rss-1ec656e84339------2</link>
            <guid isPermaLink="false">https://medium.com/p/c745b4a90f1f</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[ai-observability]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <dc:creator><![CDATA[Sai Charan J]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 13:52:40 GMT</pubDate>
            <atom:updated>2026-11-09T13:52:40.000Z</atom:updated>
            <content:encoded><![CDATA[<p>Every AI application on our platform sends its traces to one place: an in-house <strong>observability collector</strong>. It accepts OpenTelemetry (OTLP) traces, replies right away, and forwards them to the right places: our LLM observability backend, any other OTLP destination we configure, and blob storage for analytics.</p><p>Today it handles about <strong>150 million traces a day</strong> on a small footprint. The first version didn’t. It had a problem that only showed up under load and never appeared in a status code. This post covers why we built the collector, what went wrong, and how we fixed it.</p><h3>Why have our own collector?</h3><p>The simplest option is to give every team the vendor’s endpoint and API key and let them export directly. We decided against it, for four reasons:</p><ul><li><strong>Changing vendors shouldn’t mean changing every app.</strong> If every application points at the vendor, a migration touches every application. With one internal endpoint, apps keep sending to the same place and only the collector changes.</li><li><strong>One way to authenticate.</strong> Apps use the same client credentials they use everywhere else on the platform. The collector maps each client to the right backend workspace and credentials, so vendor keys never leave the platform.</li><li><strong>Control over what gets created downstream.</strong> The collector stamps a project name on every trace, so the backend’s projects stay organized by client instead of being created ad hoc.</li><li><strong>One trace in, many copies out.</strong> A single trace can go to the observability backend, to other destinations, and to storage, without the application knowing or caring.</li></ul><p><strong>Why not the standard OpenTelemetry Collector?</strong> We looked at it first. The deciding factor was authentication: our client authentication and per-client credential lookup are specific to our platform, and the standard collector doesn’t support them out of the box. So we wrote a small async Python service (FastAPI + asyncio) instead.</p><h3>The problem: a pass-through that dropped half the traces</h3><p>The first version was a straight pass-through. For each incoming request it:</p><ol><li>returned 200 OK immediately,</li><li>parsed the payload in a background task,</li><li>made the outbound export call(s) to the backend.</li></ol><p>That meant the backend saw exactly our inbound traffic, with every spike passed through one-to-one. It was sometimes more than one-to-one, because a single request could fan out into more than one export.</p><p>Under high load, the backend started throttling us with RESOURCE_EXHAUSTED, UNAVAILABLE and 429 errors. Our own retry logic then made things worse:</p><ul><li><strong>Linear backoff, no jitter (1s, 2s, 3s).</strong> Hundreds of in-flight requests failed together and retried together, so they hit the backend again at the same moments.</li><li><strong>No batching.</strong> The outbound call rate always matched the inbound request rate.</li><li><strong>No circuit breaker.</strong> We kept sending traffic to an endpoint that was clearly overloaded.</li><li><strong>No per-destination limits.</strong> One global cap bounded the background work, but nothing bounded the calls to each destination.</li></ul><p>After three attempts the trace was dropped, and the caller had already received 200 OK, so nothing upstream looked wrong.</p><p>A load test made the problem visible. We ran the same script and traffic mix against both paths, about 40,000 requests each:</p><ul><li><strong>Direct to the backend:</strong> about 1% of traces missing</li><li><strong>Through our collector:</strong> about <strong>50%</strong> of traces missing</li></ul><p>Neither run had a single HTTP failure. We only saw the losses when we counted traces on the other side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GleDams0jesqZTiadSb-PA.png" /></figure><p><em>When you acknowledge before you deliver, every failure after the acknowledgement is silent. You have to measure on the far side.</em></p><h3>The fix: decouple accepting from sending</h3><p>The fix comes down to one idea: <strong>accept traces as fast as clients send them, but send them downstream only as fast as each destination can take them.</strong> A buffer sits between those two rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_sM7kTcgM91xvF1kgboFw.png" /></figure><p><strong>How one trace moves through the collector:</strong></p><ol><li>An application or the AI gateway sends OTLP protobuf with its client credentials.</li><li>The <strong>ingest API</strong> checks the client’s credentials, schedules a background task and returns 200 straight away.</li><li>The <strong>trace dispatcher</strong> parses the payload once, splits it by trace ID, stamps the project name, and queues a copy for the <strong>blob writer</strong>.</li><li>For each active destination, the dispatcher decides whether the trace belongs there, resolves that destination’s endpoint and credentials, and hands the trace to the destination’s <strong>batch sink</strong>.</li><li>Each batch sink buffers traces, merges them into batches and sends them at a pace the destination can handle, retrying or backing off when needed.</li><li>In parallel, the <strong>destination registry</strong> keeps the list of sinks in sync with the config database, which is managed through APIs.</li></ol><p>The rest of this section walks through those pieces.</p><h3>1. Accept fast, process in the background</h3><p>The ingest API authenticates the caller, hands the payload to a background task and returns. A semaphore caps how many background dispatches can run at once, so a burst can’t exhaust the process.</p><pre>@router.post(&quot;/traces&quot;)<br>async def receive_traces(request: Request, client=Depends(authenticate_client)):<br>    body = await request.body()<br>    asyncio.create_task(safe_dispatch(body, client))   # fire and forget<br>    return {&quot;message&quot;: &quot;Trace Received&quot;}</pre><pre>async def safe_dispatch(body, client):<br>    async with dispatch_semaphore:                     # bounded background work<br>        try:<br>            await dispatcher.dispatch(body, client)<br>        except Exception:<br>            logger.exception(&quot;dispatch failed&quot;)        # never takes the worker down</pre><p>The dispatcher parses the protobuf <strong>once</strong>, splits it into per-trace chunks, stamps the project name, and gives each destination the chunks meant for it. It never makes a network call itself.</p><h3>2. One resilient sink per destination</h3><p>Each destination gets its own <strong>batch sink</strong>. All of the protection lives in this one class, so every new destination gets it automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E58KqyUc-jMD_d0U9Z7p6Q.png" /></figure><ul><li><strong>Buffer.</strong> Chunks go into an in-memory FIFO (collections.deque guarded by an asyncio.Lock) with a running byte count. Buffers are keyed by endpoint <em>and</em> credentials, so traces belonging to different tenants are never merged into one batch.</li><li><strong>Flush on size or time, whichever comes first.</strong> A full buffer (3 MB by default) flushes immediately. A background ticker flushes anything older than the flush interval (1 second by default), so low-traffic clients still see their traces in near real time.</li><li><strong>Merge before sending.</strong> A flush takes chunks up to the batch cap and merges them into a single OTLP export, so many small calls become a few larger ones.</li><li><strong>Bounded memory.</strong> If a destination stays down long enough for its buffer to fill, the oldest traces are dropped first, and every drop is logged and counted.</li></ul><pre>async def submit(self, chunks, *, endpoint, headers):<br>    buf = await self._buffer_for(endpoint, headers)<br>    async with buf.lock:<br>        for chunk in chunks:<br>            size = chunk.ByteSize()<br>            if buf.size + size &gt; self.cfg.queue_max_bytes:<br>                self._drop_oldest(buf, size)              # bounded memory<br>            buf.entries.append(chunk)<br>            buf.size += size<br>        full = buf.size &gt;= self.cfg.max_batch_bytes<br>    if full:<br>        asyncio.create_task(self._flush(buf))             # size trigger<br>    # the time trigger runs in a background ticker</pre><p>Why deque + asyncio.Lock rather than queue.Queue? The exporters are natively async (grpc.aio, httpx.AsyncClient), so there’s no blocking I/O to move onto a thread. A thread-safe queue would either block the event loop or add a thread for no benefit.</p><h3>3. A send path that backs off</h3><p>Each merged batch goes through the same steps before it leaves the process:</p><ul><li><strong>Concurrency limit:</strong> at most N batches in flight per destination.</li><li><strong>Rate limit (optional):</strong> a token bucket, in requests per second, set per destination.</li><li><strong>Circuit breaker:</strong> after N consecutive failures, stop sending for a cooldown period instead of adding to the overload.</li><li><strong>Retry with exponential backoff and jitter:</strong> retries spread out over time instead of arriving together.</li><li><strong>Fail fast:</strong> auth errors, invalid payloads and other 4xx responses (except 429) are never retried, because retrying won’t change the result.</li></ul><pre>async def _send_with_retry(self, batch, endpoint, headers) -&gt; bool:<br>    delay = 1.0<br>    for attempt in range(1, self.cfg.max_retry_attempts + 1):<br>        try:<br>            if await self.client.send(batch, endpoint, headers):<br>                return True<br>        except NonRetryableSendError:<br>            return False                                  # 4xx / auth: don&#39;t retry<br>        if attempt &lt; self.cfg.max_retry_attempts:<br>            await asyncio.sleep(delay + random.uniform(0, delay))   # backoff + jitter<br>            delay *= 2<br>    return False</pre><p>One detail that mattered in practice: when a gRPC call returns UNAVAILABLE, the client closes its cached channel, so the next attempt opens a fresh connection instead of reusing one that a load balancer has already closed.</p><h3>4. Destinations are configuration, not code</h3><p>Destinations are stored in a database table and managed through CRUD APIs. Each entry holds the endpoint, the transport (gRPC or HTTP), TLS settings and headers, plus optional thresholds: batch size, flush interval, concurrency, rate limit, retries and circuit-breaker settings. Conditional routing, where only some traces go to a destination, is supported as well.</p><pre>{<br>  &quot;name&quot;: &quot;analytics-pipeline&quot;,<br>  &quot;transportType&quot;: &quot;grpc&quot;,<br>  &quot;endpointUrl&quot;: &quot;https://otel.example.internal:4317&quot;,<br>  &quot;tlsVerify&quot;: true,<br>  &quot;headers&quot;: { &quot;x-team&quot;: &quot;platform&quot; },<br>  &quot;batchConfig&quot;: { &quot;maxBatchBytes&quot;: 2000000, &quot;flushInterval&quot;: 1.0, &quot;rateLimitQps&quot;: 50 }<br>}</pre><p>The collector loads every active destination at startup and then refreshes on an interval:</p><ul><li>Unchanged destinations keep their sink, buffer and open connections.</li><li>New or changed destinations get a fresh sink.</li><li>Removed or disabled destinations flush what’s left in their buffer before shutting down.</li><li>An invalid entry is logged and skipped without affecting the others.</li></ul><p><strong>Adding a new destination takes one API call, with no code change and no redeploy.</strong></p><h3>5. A copy for analytics</h3><p>Separately from the configured destinations, every trace is also written to blob storage. Writes are batched through a queue and a background thread (the storage SDK is blocking, so it stays off the event loop), and our lakehouse jobs pick the files up from there for downstream processing.</p><h3>Under the hood: classes and design patterns</h3><p>Every class has one job, and every “what if we need X?” question has one obvious place where the change goes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkcCVCekpXdNVb-4wcfy2A.png" /></figure><ul><li><strong>TraceSinkClient: Strategy.</strong> An abstract interface with three members: send(), stats and close(). It has two implementations, OtlpGrpcExporterClient and OtlpHttpExporterClient. They only handle the wire: TLS, headers and connection reuse. They contain no batching or retry logic.</li><li><strong>SinkClientFactory: Factory.</strong> Reads a destination’s config row and returns the right client for its transport. Nothing else constructs clients.</li><li><strong>SinkConfig: Value object.</strong> A frozen dataclass holding every tunable: batch size, flush interval, queue cap, concurrency, rate limit, retries and breaker settings. from_row() builds it from the destination’s config and falls back to sensible defaults for anything that isn’t set.</li><li><strong>ResilientBatchSink: Decorator + Circuit Breaker.</strong> Wraps any TraceSinkClient and adds buffering, batching, limits, retries and the breaker. The client underneath doesn’t know any of it exists.</li><li><strong>SinkRoute + </strong><strong>CollectorEndpointRegistry: Registry / route table.</strong> A route pairs a destination’s rules with its sink. The registry builds the routes from the database, keeps them current, and swaps the whole list in one step, so the dispatcher never sees a half-updated list.</li><li><strong>RuleEvaluator and </strong><strong>CredsResolver: Interpreter over data.</strong> Routing rules and credential lookups are stored as JSON and evaluated by registered functions. Nothing is ever eval()’d.</li><li><strong>TraceDispatcher: Orchestrator.</strong> Parses once, then asks each route three questions: does this trace match, which credentials, which sink? It has no knowledge of any specific vendor.</li></ul><p><strong>How the patterns pay off</strong></p><ul><li><strong>A new destination is a database row.</strong> Factory, value object and registry together mean no code change.</li><li><strong>A new transport is one class.</strong> Thanks to Strategy, nothing else in the pipeline changes.</li><li><strong>Resilience is written once.</strong> Thanks to Decorator, every destination, current or future, gets the same batching, retries and breaker.</li><li><strong>Failures stay contained.</strong> Each destination has its own buffer, limits and breaker (the bulkhead pattern), so one slow backend can’t stall the others.</li><li><strong>Each piece is easy to test.</strong> With single-responsibility classes, a fake TraceSinkClient is enough to test batching, retries and the breaker without a network.</li></ul><h3>Results</h3><ul><li><strong>~150 million traces a day</strong></li><li><strong>3 pods</strong>, each running <strong>2 Uvicorn workers</strong>, with 2 vCPU and 6 GB of memory</li><li><strong>Near-zero drops</strong>, down from ~50% in the original load test</li><li><strong>No added latency for callers:</strong> the response goes out before any downstream work starts, and traces still arrive in near real time</li></ul><p>However spiky the inbound traffic gets, the backend now receives steady, batched traffic at a rate we control.</p><h3>Trade-offs</h3><p><strong>What we gained</strong></p><ul><li><strong>Vendor independence:</strong> clients don’t change when a backend does.</li><li><strong>Steady downstream load:</strong> batching and rate limits turn spikes into a steady stream.</li><li><strong>Isolation:</strong> each destination has its own buffer, limits and circuit breaker, so one slow destination doesn’t hold up the others.</li><li><strong>Extensibility:</strong> a new destination is a config entry, not a code change.</li><li><strong>Central control:</strong> auth, project naming and fan-out all live in one place.</li></ul><p><strong>What it costs</strong></p><ul><li><strong>200 OK means accepted, not delivered.</strong> The caller can’t see delivery problems, so we watch per-sink metrics instead: success and failure counts, overflow drops and breaker state.</li><li><strong>Best effort, not exactly once.</strong> Overflow drops the oldest traces, and an open breaker skips batches. That’s the right trade-off for telemetry; it would be the wrong one for payments.</li><li><strong>Limits are per worker process.</strong> A limit of 10 requests per second on 3 pods × 2 workers is really 60 requests per second in total. Set the values with that in mind, or add shared coordination if you need a hard global cap.</li><li><strong>Buffers live in memory.</strong> A crash loses whatever hasn’t been flushed yet. A graceful shutdown drains first.</li><li><strong>Config changes aren’t instant.</strong> Each worker picks them up on its next refresh.</li><li><strong>One more service to run.</strong> It’s another hop to deploy, scale and monitor.</li></ul><h3>Takeaways</h3><ol><li><strong>Separate the accept path from the send path.</strong> Don’t let an upstream spike turn into a downstream spike.</li><li><strong>Add jitter to retries.</strong> Without it, a brief slowdown becomes a retry storm.</li><li><strong>Put the resilience in one reusable component</strong>, and make destinations configuration rather than code.</li><li><strong>Put the resilience in one reusable component</strong>, and make destinations configuration rather than code.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c745b4a90f1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>