Skip to Content
Kido Bag
Domain Combo SuitesPillar 2. High-Concurrency & Caching

@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:

  1. 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.
  2. 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.
  3. 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.
  4. 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 \uFFFD corrupted glyphs in client UIs.

πŸ›οΈ 3-Tier Production Evolution Ladder

Scale DimensionTier 1 (SME Zero-Infra)Tier 2 (Growth & Production Copilot)Tier 3 (Big-Tech Standard)
ArchitectureIn-Memory Token Stream Synthesizer (Tier0CachedChunkStreamer)Direct Provider SSE Proxy + Edge Anti-Buffering + Rate GuardDistributed Multi-Node Pub/Sub SSE Fanout (Redis/Valkey)
Infra & Cost\$0 extra (Cached canned responses, zero LLM tokens)\$15/mo VPS + Provider TokensMulti-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 lookups0.0273Β’/task (GonnaCrash L02 Record)Elastic token tier fallback
429 ResilienceZero API calls neededDual RPM/TPM Token Bucket + Full Jitter BackoffActive-Active multi-provider automated failover
Architecture BlueprintMermaid
Compiling architecture diagram...

πŸ“¦ 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-8
    • Cache-Control: no-cache, no-transform
    • X-Accel-Buffering: no (disables Nginx micro-caching)
    • Connection: keep-alive
  • generateCaddySseProxyConfig(): Outputs Caddy configuration with flush_interval -1.

2. Multi-Byte UTF-8 Protocol & Parsers (src/sse-protocol.ts)

  • SseStreamParser: Streaming event parser using native TextDecoder({ 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 standard data: [DONE]\n\n termination frame.

3. ReadableStream Synthesis Engine (src/readable-stream-engine.ts)

  • createSseTokenReadableStream(tokens, options): Converts arrays or generators into WHATWG ReadableStream instances 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 MetricBlocking HTTP (Naive)Streaming SSE (@kido/ai-stream)Target SLAAchievement
Time-to-First-Token (TTFT)4,200 ms345 ms<= 2,000 msπŸ† 91.8% Latency Reduction
Response Success Rate92% (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 DiacriticsHigh corruption riskZero corruption (Stream TextDecoder)100% CleanZero character drops

πŸš€ Surgical Extraction & CLI Installation

# Install directly via Kido CLI
npx @kido/cli add @kido/ai-stream

On this page