DBRaven
Full ReviewModerate Readinessdraft

Architecture Review: AI Retrieval-Augmented Generation Platform

A Retrieval-Augmented Generation (RAG) architecture that combines vector similarity search for semantic document retrieval with relational metadata filtering, using PostgreSQL with pgvector as the unified store for both embeddings and structured data. Redis provides a semantic cache to avoid redundant embedding model inference and reduce vector index query load for repeated or similar queries. Kafka manages the asynchronous embedding generation pipeline that keeps the vector index current as source documents are added or updated.

Evidence Confidence

Moderate

moderate

Executive Summary

AI Retrieval-Augmented Generation Platform: moderate operational readiness (78% evidence confidence). 0 architectural strengths identified, 4 operational risks to manage. Primary concern: Memory Pressure and OOM Kill. Requires Advanced operational maturity.

Readiness Rationale

Overall moderate readiness across 8 dimensions. Weak: consistency. Limited: team maturity. Strong: operational, migration, observability.

Key Concerns

  • !Memory Pressure and OOM Kill
  • !Thundering Herd (Cache Stampede)

Key Strengths

  • +Architecture is well-defined for the ai rag application problem profile

8

Assessments

3

Tradeoffs

6

Sections

11

Recommendations

Readiness Assessments

8

Architectural Tradeoffs

3

Recommendations

11
High

Monitor: Thundering Herd (Cache Stampede)

risk_monitoring

When a popular cached key expires or a service recovers from downtime, all requests that were waiting or arrive simultaneously miss the cache and hit the origin database concurrently, producing a request spike that can overwhelm the database within seconds.

Affects 1 node. (Redis)

High

Monitor: Memory Pressure and OOM Kill

risk_monitoring

When total memory demand from a process or the entire host exceeds available physical RAM plus swap, the Linux OOM killer terminates one or more processes to reclaim memory, causing immediate connection loss, data corruption risk if in-flight writes are lost, and process restart overhead.

Affects 1 node. (AI Embedding Lookup)

High

Implement: Monitor generic risk probe signals

observability

Seed 'Thundering Herd (Cache Stampede) Risk Probe' identifies 2 metrics relevant to thundering_herd.

Metrics to instrument: error_rate, p95_latency_ms

Moderate

LLM application with no retrieval augmentation (prompt-only context) → PostgreSQL + pgvector for semantic retrieval with manual embedding generation

migration_planning

Trigger: LLM responses requiring more factual accuracy or domain-specific context; context window limitations requiring selective document retrieval; user queries returning hallucinated answers that could be grounded with retrieval. Migrate from 'LLM application with no retrieval augmentation (prompt-only context)' to 'PostgreSQL + pgvector for semantic retrieval with manual embedding generation'. Start with synchronous embedding generation on write and exact ANN search. Introduce asynchronous pipeline and approximate indexes once baseline retrieval quality and query volume are understood.

Embedding model selection is a significant decision: dimension size affects index size, query latency, and migration cost if the model is changed later; Naive cosine similarity without metadata filtering returns semantically related but contextually wrong results (e.g., wrong tenant, wrong time range)

Moderate

Synchronous embedding generation on write path → Asynchronous embedding pipeline via Kafka consumer

migration_planning

Trigger: Document ingestion p99 > 500ms due to embedding API call in write path; embedding API rate limits blocking document writes during traffic spikes. Migrate from 'Synchronous embedding generation on write path' to 'Asynchronous embedding pipeline via Kafka consumer'. Decouple embedding generation from document writes before the write path latency becomes user-visible. The Kafka-backed pipeline also provides natural rate limiting against embedding API quotas.

Asynchronous pipeline introduces a retrieval lag window: must be communicated in product UX (e.g., "indexing in progress"); Consumer failure requires replay from Kafka offset: embedding API idempotency must be verified

Moderate

Prepare runbook for: Burst Traffic Cold Cache Stampede

simulation_preparedness

Simulation demonstrates critical degradation of redis, postgresql

Without a runbook, recovery from this failure mode will be ad-hoc

burst-traffic-cold-cache-stampede
Moderate

Prepare runbook for: Connection Pool Exhaustion with Horizontal User Scale

simulation_preparedness

Simulation demonstrates critical degradation of postgresql

Without a runbook, recovery from this failure mode will be ad-hoc

connection-pool-growth-with-user-scale
Moderate

Plan evolution: OLTP Analytics Queries → OLTP + OLAP Separation

evolution_planning

Evolution from Unified OLTP + Analytics on PostgreSQL → Separated OLTP (PostgreSQL) + OLAP (ClickHouse/Snowflake)

Migration complexity: medium. Rollback: always.

oltp-analytics-to-separated
Moderate

Plan evolution: Single Cache Layer → Distributed Cache

evolution_planning

Evolution from Single Redis Node / Sentinel Cluster → Distributed Redis Cluster (Consistent Hash Ring)

Migration complexity: medium. Rollback: complex.

single-cache-to-distributed
Low

Monitor threshold: Tier 1: Vector Index Recall Degradation

scaling_monitoring

Signal: Retrieval quality metrics (MRR, NDCG) declining despite stable query volume; users reporting irrelevant context being surfaced; pgvector IVFFlat probes set below recommended value for current document count

Bottleneck: IVFFlat index not rebuilt after significant document additions; or probes too low for current index size. Evolution: Schedule periodic index rebuilds triggered by document count growth (e.g., rebuild at 2x the document count present at last index build); increase ivfflat.probes to improve recall at cost of query latency; evaluate HNSW for recall-critical workloads

Low

Monitor threshold: Tier 2: PostgreSQL Memory Pressure from Vector Operations

scaling_monitoring

Signal: PostgreSQL process memory > 8GB; OOM killer events on the database host; vector query p99 latency increasing as shared_buffers evicts vector index pages; pg_stat_bgwriter showing high buffers_clean rate

Bottleneck: Vector index (HNSW or large IVFFlat) and embedding storage competing with relational data for shared_buffers. Evolution: Increase PostgreSQL shared_buffers to 40% of available RAM; move vector tables to a dedicated tablespace on NVMe; partition large vector tables by document category to reduce per-query index scan range; evaluate dedicated pgvector replica for query isolation

Scaling Pressure Signals

8

Retrieval quality metrics (MRR, NDCG) declining despite stable query volume; users reporting irrelevant context being surfaced; pgvector IVFFlat probes set below recommended value for current document count

Threshold

Tier 1: Vector Index Recall Degradation

Likely Bottleneck

IVFFlat index not rebuilt after significant document additions; or probes too low for current index size

Recommended Evolution

Schedule periodic index rebuilds triggered by document count growth (e.g., rebuild at 2x the document count present at last index build); increase ivfflat.probes to improve recall at cost of query latency; evaluate HNSW for recall-critical workloads

PostgreSQL process memory > 8GB; OOM killer events on the database host; vector query p99 latency increasing as shared_buffers evicts vector index pages; pg_stat_bgwriter showing high buffers_clean rate

Threshold

Tier 2: PostgreSQL Memory Pressure from Vector Operations

Likely Bottleneck

Vector index (HNSW or large IVFFlat) and embedding storage competing with relational data for shared_buffers

Recommended Evolution

Increase PostgreSQL shared_buffers to 40% of available RAM; move vector tables to a dedicated tablespace on NVMe; partition large vector tables by document category to reduce per-query index scan range; evaluate dedicated pgvector replica for query isolation

Evidence:kafka-consumer-lag-cascadepartition-hotspot-amplification

Kafka consumer group lag growing for the embedding generation consumer; document ingestion reporting "indexing pending" status for > 5 minutes; embedding API rate limit errors in consumer logs

Threshold

Tier 3: Embedding Pipeline Backlog

Likely Bottleneck

Embedding model inference throughput (tokens/sec) insufficient for document ingestion rate

Recommended Evolution

Increase embedding consumer parallelism (capped at Kafka partition count); batch documents per embedding API call to improve inference efficiency; implement priority queuing to index recent documents ahead of backlog

Evidence:kafka-consumer-lag-cascadepartition-hotspot-amplification

pgvector ANN query p99 > 100ms at > 20M vectors with HNSW; PostgreSQL unable to serve concurrent relational and vector queries without I/O contention; index rebuild duration > 4 hours

Threshold

Tier 4: Scale Ceiling for pgvector

Likely Bottleneck

pgvector reaching practical scale ceiling for single-node HNSW at large vector counts

Recommended Evolution

Evaluate dedicated vector database (Qdrant, Weaviate) for the vector search path while retaining PostgreSQL for relational metadata; implement a hybrid query layer that fetches candidate IDs from the vector store and hydrates with PostgreSQL metadata

Retrieval quality metrics (MRR, NDCG) declining despite stable query volume; users reporting irrelevant context being surfaced; pgvector IVFFlat probes set below recommended value for current document count

Threshold

Escalation trigger: IVFFlat index not rebuilt after significant document additions; or probes too low for current index size

Likely Bottleneck

Tier 1: Vector Index Recall Degradation

Recommended Evolution

Monitor: error_rate, p95_latency_ms

PostgreSQL process memory > 8GB; OOM killer events on the database host; vector query p99 latency increasing as shared_buffers evicts vector index pages; pg_stat_bgwriter showing high buffers_clean rate

Threshold

Escalation trigger: Vector index (HNSW or large IVFFlat) and embedding storage competing with relational data for shared_buffers

Likely Bottleneck

Tier 2: PostgreSQL Memory Pressure from Vector Operations

Recommended Evolution

Monitor: error_rate, p95_latency_ms

Kafka consumer group lag growing for the embedding generation consumer; document ingestion reporting "indexing pending" status for > 5 minutes; embedding API rate limit errors in consumer logs

Threshold

Escalation trigger: Embedding model inference throughput (tokens/sec) insufficient for document ingestion rate

Likely Bottleneck

Tier 3: Embedding Pipeline Backlog

Recommended Evolution

Monitor: error_rate, p95_latency_ms

pgvector ANN query p99 > 100ms at > 20M vectors with HNSW; PostgreSQL unable to serve concurrent relational and vector queries without I/O contention; index rebuild duration > 4 hours

Threshold

Escalation trigger: pgvector reaching practical scale ceiling for single-node HNSW at large vector counts

Likely Bottleneck

Tier 4: Scale Ceiling for pgvector

Recommended Evolution

Monitor: error_rate, p95_latency_ms

Migration Readiness

12

Migration Stages

3
Stage

LLM application with no retrieval augmentation (prompt-only context) → PostgreSQL + pgvector for semantic retrieval with manual embedding generation

info

Migration trigger: LLM responses requiring more factual accuracy or domain-specific context; context window limitations requiring selective document retrieval; user queries returning hallucinated answers that could be grounded with retrieval

Stage

Synchronous embedding generation on write path → Asynchronous embedding pipeline via Kafka consumer

info

Migration trigger: Document ingestion p99 > 500ms due to embedding API call in write path; embedding API rate limits blocking document writes during traffic spikes

Stage

Single pgvector index serving all document types → Partitioned vector indexes per document namespace or tenant

info

Migration trigger: Index scan range too large for per-query latency targets; tenant isolation requirements demand separate vector spaces; different document types requiring different embedding models or dimensions

!

Risks

9
Risk

Embedding model selection is a significant decision: dimensi

warning

Embedding model selection is a significant decision: dimension size affects index size, query latency, and migration cost if the model is changed later

Risk

Naive cosine similarity without metadata filtering returns s

warning

Naive cosine similarity without metadata filtering returns semantically related but contextually wrong results (e.g., wrong tenant, wrong time range)

Risk

Asynchronous pipeline introduces a retrieval lag window: mus

warning

Asynchronous pipeline introduces a retrieval lag window: must be communicated in product UX (e.g., "indexing in progress")

Risk

Consumer failure requires replay from Kafka offset: embeddin

warning

Consumer failure requires replay from Kafka offset: embedding API idempotency must be verified

Risk

Multiple indexes multiply rebuild and monitoring overhead

warning
Risk

Cross-namespace retrieval requires fan-out queries across mu

warning

Cross-namespace retrieval requires fan-out queries across multiple indexes

Risk

Projection lag creates a read-after-write window where users

critical

Projection lag creates a read-after-write window where users see stale data after their own writes. Mitigation: Route immediate post-write reads to the write store (session-scoped write token); accept eventual consistency only for non-user-initiated reads

direct-db-to-cqrs

Risk

Projection rebuild after schema change can take hours or day

critical

Projection rebuild after schema change can take hours or days on large datasets. Mitigation: Design blue/green projection deployment: build new projection in parallel before switching traffic; test rebuild time in staging

direct-db-to-cqrs

Risk

Cross-service workflows that previously used database transa

critical

Cross-service workflows that previously used database transactions now require Saga orchestration. Mitigation: Design idempotent event handlers; implement compensating transactions for every multi-step workflow; test failure injection in staging

modular-monolith-to-event-driven

Review Sections

6

Referenced Intelligence

kafkapostgresqlredisburst-traffic-cold-cache-stampedeconnection-pool-growth-with-user-scalecqrs-projection-lag-expansioncross-region-stale-read-windowdistributed-cache-invalidation-failureevent-replay-storm-recoverykafka-consumer-lag-cascademulti-tenant-noisy-neighborpartition-hotspot-amplificationpostgresql-replication-lag-surgequery-cost-without-indexesread-amplification-n-plus-one-queriesredis-cache-collapse-stampederetry-storm-amplificationsplit-brain-during-network-partitionstorage-bloat-without-archivingstorage-cost-compounding-without-retentionwrite-heavy-bulk-import-saturationdirect-db-to-cqrsmodular-monolith-to-event-drivenoltp-analytics-to-separatedpostgresql-to-partitionedrabbitmq-to-kafkasingle-cache-to-distributedsingle-region-to-multi-regionarchitecture-evolutionauditabilitybtree-indexingcache-invalidationcap-theoremconsistency-modelscqrs-operationalevent-sourcingeventual-consistencykafka-consumer-lagmulti-tenancynormalizationoltp-vs-olappartition-hotspotsquery-planningqueue-backlogreplication-lagvector-databaseswrite-amplification