AI Platform: Shared AI Infrastructure & RAG Pipeline
Architecting a centralized microservice gateway with Qdrant vector retrieval, Redis semantic caching, and tenant-isolated execution.
Executive Summary
When building multiple client applications requiring LLM integration, duplicating prompt logic, model clients, rate limiting, and vector embeddings across repositories quickly causes cost blowouts and divergent behavior. This case study explores the centralized AI Platform—a dedicated NestJS microservice that unifies LLM orchestration, hybrid RAG over Qdrant, semantic caching with Redis, and tenant isolation through API keys.
The Engineering Challenge & Context
As the ecosystem grew to include five consumer products (Travel Planner, Movie Matcher, Sports Tracker, Study Spot Finder, Hiking Explorer) and an internal portfolio chatbot, each application initially managed its own LLM API keys and retrieval mechanisms. This resulted in three distinct operational bottlenecks: 1) Redundant API billing for semantically equivalent queries across users; 2) Inability to apply global rate limits, causing sudden 429 quota exhaustion; and 3) Inconsistent retrieval quality due to fragmented vector index configurations.
System Architecture & Data Flow
The AI Platform sits as a horizontal infrastructure service between frontend client applications and upstream model providers (Gemini 2.0 Flash, OpenAI GPT-4o). Clients communicate exclusively over an authenticated REST gateway (`POST /api/v1/ai/chat`) providing an application ID and API key. Requests first pass through an in-memory rate limiter, followed by a Redis semantic cache lookup. If an embedding match is found with cosine similarity >= 0.92, the cached completion is returned in under 15ms. Otherwise, the platform retrieves relevant document chunks from Qdrant vector collections, builds a structured prompt, invokes the upstream LLM with fallback policies, and writes the response asynchronously to the cache.
+-----------------------------------------------------------------------------------+
| CLIENT APPLICATIONS |
| Travel Planner | Movie Matcher | Sports Tracker | Portfolio Chatbot |
+-----------------------------------------------------------------------------------+
|
| POST /api/v1/ai/chat
| Headers: x-api-key, Content-Type: json
v
+-----------------------------------------------------------------------------------+
| CENTRALIZED AI PLATFORM (NestJS) |
| |
| [ Auth & Rate Limiting ] ---> Validate x-api-key per tenant & check sliding token |
| | |
| v |
| [ Semantic Cache Check ] ---> Redis Cosine Similarity Query (Threshold: 0.92) |
| | | |
| | (Hit: <15ms) | (Miss) |
| v v |
| Return Cache [ Vector Retrieval ] ---> Qdrant Hybrid Collection Search |
| | |
| v |
| [ LLM Gateway ] ---> Primary: Gemini 2.0 / OpenAI |
| | Fallback: Exponential Backoff + Secondary |
| v |
| [ Telemetry ] ---> Log latency, token count, cost to PostgreSQL |
| | |
| +---------> Write to Redis Semantic Cache |
+-----------------------------------------------------------------------------------+Key Engineering Decisions & Trade-offs
Centralized Microservice vs. Shared NPM Package
Rationale: An NPM package would embed provider API keys into client build artifacts or require every microservice to maintain secure secret rotation. A centralized service concentrates secret management, allows zero-downtime model routing upgrades, and provides global cost telemetry in one location.
Trade-offs & Constraints: Introduces an extra network hop (approx 10-25ms internal latency). Mitigated by deploying on the same cloud region and employing Redis semantic caching.
Redis Vector Similarity Caching vs. Exact String Match
Rationale: Users frequently pose identical questions with slight syntactic variations (e.g., 'What is Rishank's experience in Kafka?' vs. 'How much Kafka experience does Rishank have?'). String-based hash caching yields less than 8% hit rates in chat workloads, whereas semantic cosine similarity on prompt embeddings achieved a 34% cache hit rate in testing.
Trade-offs & Constraints: Requires computing an embedding for every incoming prompt before checking cache. However, embedding latency (30-40ms) is an order of magnitude lower than full generative LLM completion (800-2500ms).
Qdrant Vector Database for RAG Collections
Rationale: Qdrant offers native payload filtering alongside dense vector search, enabling tenant isolation within shared collections (filtering by `tenant_id` and `application_id` without creating distinct vector clusters per app).
Trade-offs & Constraints: Requires dedicated RAM allocation for vector index payloads compared to purely serverless managed vector stores, but delivers deterministic sub-20ms retrieval times.
API Gateway Contract & Request Flow
The core gateway interface exposes `POST /api/v1/ai/chat`. The endpoint mandates strict payload validation using NestJS Class-Validator, verifying tenant scopes before any downstream invocation occurs.
export interface AIChatRequestDto {
applicationId: 'portfolio' | 'travel-planner' | 'movie-matcher' | 'sports-tracker';
tenantId: string;
message: string;
useRag?: boolean;
useMemory?: boolean;
cacheable?: boolean;
temperature?: number;
metadata?: {
source?: string;
clientIp?: string;
};
}
export interface AIChatResponseDto {
role: 'assistant';
content: string;
cached: boolean;
latencyMs: number;
tokensUsed?: {
prompt: number;
completion: number;
};
source: 'semantic-cache' | 'qdrant-rag' | 'llm-direct';
}Semantic Cache Lookup Mechanics
When a request arrives with `cacheable: true`, the system generates a 768-dimensional text embedding. It queries Redis using RedisVL / RediSearch vector indexes. If the closest vector has cosine similarity exceeding 0.92, the stored response is returned immediately, bypassing LLM billing.
async function findCachedCompletion(
embedding: number[],
applicationId: string
): Promise<string | null> {
const query = '@applicationId:{' + applicationId + '} => [KNN 1 @vector $vec AS score]';
const result = await redisClient.ft.search('idx:semantic_cache', query, {
PARAMS: { vec: Buffer.from(new Float32Array(embedding).buffer) },
RETURN: ['response', 'score'],
DIALECT: 2,
});
if (result.total > 0) {
const topMatch = result.documents[0];
const similarity = 1 - parseFloat(topMatch.value.score as string);
if (similarity >= 0.92) {
return topMatch.value.response as string;
}
}
return null;
}Reliability, Security & Operational Considerations
- •Per-tenant rate limiting using sliding window counters stored in Redis.
- •Service API key authentication (`x-api-key`) with SHA-256 hash lookup in PostgreSQL.
- •Upstream timeout handling with 7.5s hard timeouts and circuit-breaking to grounded fallback documents.
- •Strict input sanitization limiting incoming prompt length to prevent token-exhaustion denial of service.
Lessons Learned
- ✓Semantic caching requires calibrated similarity thresholds: at 0.85, false positives altered answer specificity; 0.92 provided the optimal balance between accuracy and hit rate.
- ✓Multi-tenant vector collections must always use hard metadata pre-filtering; filtering post-retrieval risks returning zero candidate chunks if other tenants dominate top-k.
- ✓A centralized service drastically simplifies observability: metric dashboards on request latencies and token costs enabled targeted prompt compression across all 5 apps.
Known Limitations & Future Architecture Roadmap
- →Currently supports stateless single-turn and lightweight session context; full cross-session long-term memory graph is planned for future iterations.
- →Embedding computation on cache misses still incurs external network latency; hosting a local small embedding model on ONNX Runtime is under evaluation.