Scaling AI Analytics to Handle 1 Million Queries Per Day
Scaling AI analytics is the engineering challenge of serving millions of AI-powered queries per day while maintaining sub-second latency, high accuracy, and reasonable cost. At Skopx, our architecture target is 1 million queries per day, and reaching it means addressing four bottlenecks: LLM API throughput, database connection pooling, vector search performance, and intelligent caching. This post covers each bottleneck and the solutions we implemented on our Next.js and Supabase stack hosted on Railway.
What Are the Scaling Bottlenecks in AI Analytics?
AI analytics platforms have a fundamentally different scaling profile from traditional web applications. A typical web request reads from a database and returns JSON. An AI analytics request involves LLM API calls, vector search, database queries, and response synthesis. Each request consumes far more compute than a traditional API call.
The dominant cost is LLM API usage. At 1 million queries per day, the LLM bill is large even with a mix of Haiku and Sonnet. Without optimization, this makes the business model unsustainable. Our goal was to bring the cost of a query down while maintaining quality.
How Does the Caching Strategy Work?
Caching is the single most impactful optimization. We implement three caching layers: semantic query cache, schema cache, and embedding cache.
Semantic Query Cache. Many users ask similar questions in different words. "How many active users?" and "What's our active user count?" should return the same cached result. We hash the question's embedding vector to create a semantic cache key. If a new question's embedding is close enough to a cached question's, we return the cached result. A cache hit is served without any LLM call or database query.
// Semantic query cache
interface CachedResult {
answer: string;
citations: Citation[];
timestamp: Date;
ttl: number; // seconds
hitCount: number;
}
async function checkSemanticCache(
question: string,
orgId: string
): Promise<CachedResult | null> {
const embedding = await embedQuestion(question);
const cacheKey = roundedEmbeddingHash(embedding, 4);
// Check exact hash match first (sub-1ms)
const exact = await redis.get(`cache:${orgId}:${cacheKey}`);
if (exact) return JSON.parse(exact);
// Check semantic similarity for near-matches (5-10ms)
const nearMatch = await vectorCache.search(embedding, {
filter: { orgId },
threshold: 0.95, // cosine similarity
limit: 1
});
if (nearMatch.length > 0) {
return JSON.parse(nearMatch[0].metadata.result);
}
return null;
}
Schema Cache. Database schema introspection is expensive: every lookup queries information_schema. We cache schema metadata in memory for a short time. Schema changes are rare (most databases change schema less than once per day), so this cache rarely misses.
Embedding Cache. Pre-computed embeddings for the user's codebase and documents are stored in ChromaDB and refreshed incrementally on changes. Query-time embedding (converting the user's question to a vector) is cached briefly, since users often refine the same question multiple times.
How Does Connection Pooling Work at Scale?
Each user can connect multiple external databases to Skopx. With many concurrent users, each with more than one connected database, the number of database connections to manage grows fast. Direct connections to this many databases would exhaust file descriptors, memory, and network sockets.
We use a tiered connection pooling strategy. For Supabase databases, we route through Supabase's session pooler at pooler.supabase.com port 5432, which handles connection multiplexing on their end. For direct PostgreSQL connections, we maintain a connection pool per database, with a cap on its connections and a timeout that closes the idle ones.
The connection pool is managed per-process on Railway. With several application processes, each process manages its own pool. We use consistent hashing on the user ID to route requests to the same process, which improves cache hit rates and reduces pool fragmentation.
Connection Architecture:
User Request → Railway Load Balancer → App Process (1 of 4)
→ Supabase Pooler (for Supabase DBs) → PostgreSQL
→ Direct Pool (max 5 per DB) → External PostgreSQL
→ ChromaDB (embedded, per-process)
→ Claude API (HTTP, connection reuse)
How Do You Optimize LLM Costs?
LLM API costs are the dominant expense. We reduce them through four techniques.
Model routing. Not every query needs the most expensive model. We classify queries into three tiers: simple (direct lookups, single-table queries) use Claude 3.5 Haiku, moderate (multi-table joins, basic analysis) use Claude 3.5 Sonnet, and complex (cross-source federation, deep architectural analysis) use Claude 3.5 Sonnet with extended thinking, each tier costlier than the last. The classifier itself runs on Haiku.
In practice, most queries are not complex. This distribution plus semantic caching brings the average cost of a query down.
Prompt compression. Schema metadata, few-shot examples, and system instructions are compressed using a technique we call "structured abbreviation." Instead of sending full CREATE TABLE statements, we send a compact notation: users(id:uuid, email:text, created_at:ts, org_id:uuid→orgs.id). This sends the model fewer schema tokens.
Response streaming. Streaming does not reduce cost, but it reduces perceived latency. Users see the first tokens while a complex query is still being answered. This dramatically improves the user experience at scale.
Batch processing for insights. The insight generation pipeline runs on a cron schedule rather than in real-time. This allows us to batch multiple metrics into a single LLM call, which lowers the cost of each insight.
How Does Horizontal Scaling Work on Railway?
Railway supports horizontal scaling through multiple service instances behind a load balancer. Our application is stateless, all persistent state lives in Supabase PostgreSQL, and ChromaDB runs as an embedded database within each process with synchronized data.
We scale based on two signals: request queue depth and P95 latency. Scale-down is more conservative, we wait for a stretch of low utilization before removing an instance, to avoid thrashing during periodic traffic spikes.
Each Railway instance handles a bounded number of concurrent requests, limited primarily by the memory its ChromaDB indexes need. At 1 million queries per day, the number of concurrent requests is the daily volume times the average request duration, spread over the day, and peak traffic is a multiple of that average. That number, not the daily total, decides how many instances run.
How Do You Monitor Performance at Scale?
We track four key metrics: P50/P95/P99 latency, cache hit rate, LLM cost per query, and error rate. These are emitted as structured logs from every request and aggregated in real-time.
Alerts watch these metrics. High P95 latency triggers investigation. A low cache hit rate triggers a review of the cache configuration. A rising cost per query triggers an audit of model routing. A high error rate triggers immediate incident response.
We also track "quality at scale", whether accuracy degrades as traffic increases. Sampling responses at different traffic levels is how we check that caching and model routing do not cost accuracy.
Key Takeaways
Scaling AI analytics requires optimizing across four dimensions simultaneously: LLM costs (model routing and semantic caching), database connections (pooling through Supabase and tiered connection management), vector search (embedded ChromaDB with incremental updates), and compute (stateless horizontal scaling on Railway). The single highest-impact optimization is semantic query caching, which answers a repeated question with no LLM call at all. The key architectural principle is that AI workloads are compute-heavy but stateless, which makes horizontal scaling straightforward once you externalize all state to the database layer.
Skopx Team
The Skopx engineering and product team