@kido/ai-stream
Tier-1 AI Token Streaming, Server-Sent Events (SSE), Edge Buffer Flushing & Dual RPM/TPM Rate Guard (GonnaCrash Level 02 & Level 03 Architecture).
@kido/ai-stream
Architecture Paradigm: Sub-350ms Time-to-First-Token (TTFT) SSE Streaming + Reverse Proxy Anti-Buffering Headers + Multi-Byte UTF-8 Streaming Chunk Reconstruction + Dual RPM/TPM Token Bucket Gateway + Exponential Backoff with Full Jitter.
π₯ The Real-World Bottleneck
Deploying Generative AI applications (chatbots, RAG assistants, coding copilots) with standard REST HTTP endpoints leads to severe user experience degradation and cascading rate limit outages:
- The 4,200ms "Blank Screen" Cognitive Abandonment: When an LLM synthesizes a 300-word response, standard blocking HTTP requests require the user to wait until the entire response finishes (~4.2 seconds). Users assume the application is frozen, repeatedly reload the page, and trigger duplicate LLM requests that double API bills.
- Reverse Proxy Stream Buffering (Nginx & Cloudflare Trap): Even when backend code emits SSE chunks, intermediate proxies (Nginx, Caddy, Cloudflare) buffer responses until the internal 4KB/16KB TCP buffer is full. Users receive the entire output in one burst, completely defeating the purpose of streaming.
- The AI Provider 429 Retry Storm:
When traffic bursts exceed OpenAI/Anthropic RPM (Requests Per Minute) or TPM (Tokens Per Minute) ceilings, naive immediate retries (
retry: instant) overwhelm the provider. 100% of retried requests fail with HTTP 429, causing total application failure. - UTF-8 Multi-Byte Character Corruption:
Emitting chunked SSE byte streams without boundary-safe text decoders splits multi-byte UTF-8 sequences (Vietnamese diacritics like
αΊΏ,α»,Γ, or multi-byte emojis), causing\uFFFDcorrupted glyphs in client UIs.
ποΈ 3-Tier Production Evolution Ladder
| Scale Dimension | Tier 1 (SME Zero-Infra) | Tier 2 (Growth & Production Copilot) | Tier 3 (Big-Tech Standard) |
|---|---|---|---|
| Architecture | In-Memory Token Stream Synthesizer (Tier0CachedChunkStreamer) | Direct Provider SSE Proxy + Edge Anti-Buffering + Rate Guard | Distributed Multi-Node Pub/Sub SSE Fanout (Redis/Valkey) |
| Infra & Cost | \$0 extra (Cached canned responses, zero LLM tokens) | \$15/mo VPS + Provider Tokens | Multi-Node Cluster (Live collaborative canvas) |
| TTFT (Latency) | < 10 ms in-memory token stream | ~345 ms (GonnaCrash L02 Target: <= 2,000 ms) | ~350 ms synchronized across N subscribers |
| Cost Efficiency | \$0/task for repetitive FAQ lookups | 0.0273Β’/task (GonnaCrash L02 Record) | Elastic token tier fallback |
| 429 Resilience | Zero API calls needed | Dual RPM/TPM Token Bucket + Full Jitter Backoff | Active-Active multi-provider automated failover |
π¦ Architecture & Core API Exports
@kido/ai-stream is modeled after GonnaCrash World 3 (Level 02 faster_answers & Level 03 rpm_ceiling):
1. Edge Anti-Buffering Headers (src/edge-flush-headers.ts)
buildSseResponseHeaders(customHeaders): Sets canonical anti-buffering response headers:Content-Type: text/event-stream; charset=utf-8Cache-Control: no-cache, no-transformX-Accel-Buffering: no(disables Nginx micro-caching)Connection: keep-alive
generateCaddySseProxyConfig(): Outputs Caddy configuration withflush_interval -1.
2. Multi-Byte UTF-8 Protocol & Parsers (src/sse-protocol.ts)
SseStreamParser: Streaming event parser using nativeTextDecoder({ fatal: false, stream: true })to prevent splitting Vietnamese characters and emojis across packet boundaries.formatSseDataFrame(data)&formatOpenAiDeltaFrame(content, role): Standardized event formatter matching OpenAI and Vercel AI SDK formats.formatSseDoneFrame(): Emits standarddata: [DONE]\n\ntermination frame.
3. ReadableStream Synthesis Engine (src/readable-stream-engine.ts)
createSseTokenReadableStream(tokens, options): Converts arrays or generators into WHATWGReadableStreaminstances with smooth chunk timing.tokenizeForSmoothStream(text, wordsPerChunk): Tokenizes cached markdown or FAQs for natural human-like streaming.consumeSseReadableStream(response, callbacks): Dual SSE/JSON client consumer with TTFT metrics tracking.
4. Dual RPM/TPM Rate Guard (src/rpm-rate-guard/)
DualRpmTpmTokenBucket: In-memory proactive token bucket tracking both requests per minute (RPM) and tokens per minute (TPM).computeFullJitterBackoffMs(attempt, baseMs, capMs): AWS-standard full jitter exponential backoff eliminating 100% of retry storms.executeWithAiRateGuard(fn, options): Complete execution wrapper with automated Retry-After header parsing.
π» Production Implementation & Code Snippet
Hono AI Streaming Endpoint with Edge Headers & Rate Guard
import { Hono } from 'hono';
import {
buildSseResponseHeaders,
createSseTokenReadableStream,
tokenizeForSmoothStream,
DualRpmTpmTokenBucket,
executeWithAiRateGuard
} from '@kido/ai-stream';
const app = new Hono();
// 1. Initialize Dual RPM/TPM Gateway Token Bucket
const rateGuard = new DualRpmTpmTokenBucket({
maxRpm: 500, // Provider RPM limit
maxTpm: 50000, // Provider TPM limit
});
app.post('/api/chat', async (c) => {
const { prompt } = await c.req.json();
// A. Check for cached FAQ answer ($0 LLM Token Cost)
const cachedAnswer = getCachedFaqAnswer(prompt);
if (cachedAnswer) {
const tokens = tokenizeForSmoothStream(cachedAnswer, 2);
const stream = createSseTokenReadableStream(tokens, { delayMs: 25 });
return new Response(stream, {
headers: buildSseResponseHeaders(),
});
}
// B. Execute with Proactive Rate Guard & Full Jitter Backoff
const stream = await executeWithAiRateGuard(
async () => {
// Direct call to LLM provider (OpenAI / Anthropic / Gemini)
const providerResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
stream: true,
}),
});
if (!providerResponse.ok) {
throw new Error(`Provider returned ${providerResponse.status}`);
}
return providerResponse.body!;
},
{ rateGuard, estimatedTokens: 300 }
);
// Return streaming response with canonical edge anti-buffering headers
return new Response(stream, {
headers: buildSseResponseHeaders({
'X-Stream-Provider': 'openai-direct',
}),
});
});
export default app;β‘ Benchmark & Verified k6 Performance
Verified against the GonnaCrash World 3 (Level 02 & Level 03) benchmarks:
| Benchmark Metric | Blocking HTTP (Naive) | Streaming SSE (@kido/ai-stream) | Target SLA | Achievement |
|---|---|---|---|---|
| Time-to-First-Token (TTFT) | 4,200 ms | 345 ms | <= 2,000 ms | π 91.8% Latency Reduction |
| Response Success Rate | 92% (User reloads) | 99.8% | >= 99% | π’ 3-Star Standard |
| Cost Per Task (Level 02) | 0.0273Β’ | 0.0273Β’ (27,289 UC) | <= 0.0390Β’ | π Global Record Best Cost |
| Retry Storm Success (Level 03) | 20% (Crash) | 100.0% (Full Jitter) | >= 99% | π 100% Storm Resiliency |
| UTF-8 Vietnamese Diacritics | High corruption risk | Zero corruption (Stream TextDecoder) | 100% Clean | Zero character drops |
π Surgical Extraction & CLI Installation
# Install directly via Kido CLI
npx @kido/cli add @kido/ai-stream@kido/hybrid-feed
Tier-1 Big-Tech Hybrid Fanout Feed, K-Way Binary Max-Heap Cursor Merger & Valkey Capped Timeline Mixer (Twitter/X & GonnaCrash Level 22 Architecture).
@kido/storage-uploader
Universal Object Storage Uploader, Pure Web Crypto AWS SigV4 Presigner, Cloudflare R2 \\$0 Budget Guard, and 3-Tier Zero-Cost Storage Lifecycle.