Artag.dev
AI EngineeringPublished: 2026-11-10Updated: 2026-11-2111 min read

Cutting Production LLM Costs by 30% Using Semantic Caching and pgvector

A practical breakdown of our two-tier caching architecture (Redis exact cache + PostgreSQL pgvector semantic cache), conservative cosine similarity thresholds, tenant-safe catalog invalidation, and the benchmark behind our ~30% token reduction.

LLMpgvectorSemantic CachingRedisCost ControlRAG
~30%
Billed token reduction
0.92
Minimum cosine threshold
< 45ms
p95 semantic hit latency

Once an AI agent moves from a demo notebook to daily customer traffic across WhatsApp Business API and web chat, token spend stops being a rounding error and becomes the dominant variable cost of the product. Inside Atiende, our multi-channel conversational platform, telemetry revealed that nearly half of incoming customer questions were paraphrases of answers already computed hours earlier: product availability, shipping policies, store hours, and recurring catalog inquiries.

A naive exact-match cache misses most real users because humans rarely type identical strings twice. In this engineering note, I walk through the exact two-tier caching architecture we built—an exact normalized cache in Redis backed by a semantic cache in PostgreSQL with pgvector—that cut billed tokens per conversation by roughly 30% in project benchmarks while guaranteeing strict multi-tenant isolation and instant invalidation when catalog data changes.

When semantic caching helps—and when it becomes a production bug

The most expensive failure mode in semantic caching is not a low hit rate; it is serving a cached answer for a stateful or user-specific query. Before touching Redis or pgvector, every inbound turn must pass through a deterministic cache-eligibility gate. Any message referencing an active order status, a mutable shopping cart, personally identifiable information, or a thread already handed off to a human operator bypasses caching completely.

By contrast, stateless inquiries covering catalog facts, delivery windows, warranty rules, and payment methods exhibit high semantic repetition. Separating stateless and stateful intents upfront keeps the vector index clean, prevents false positives, and avoids paying embedding overhead on turns that should always hit live transactional tools.

  • Cacheable: catalog specifications, FAQs, shipping coverage, return policies, and standard greetings.
  • Never cache: order tracking, account balances, messages containing user IDs or PII, or post-escalation turns.
  • Hard rule: cache only the validated final user-facing response—never intermediate tool-calling payloads that embed tenant-specific database IDs.

Reference architecture: Deterministic gate, Redis exact cache, and pgvector

Before reaching OpenAI or Anthropic, an eligible message flows through three layers ordered by marginal cost and latency. Layer 0 is a deterministic short-circuit for exact SKU lookups and fixed menu commands. Layer 1 is a Redis exact cache keyed by a SHA-256 digest of the normalized prompt, tenant ID, and active catalog version.

On a Redis miss, Layer 2 embeds the normalized prompt and executes an approximate nearest-neighbor query in PostgreSQL using pgvector with an HNSW index. Only when a matching row belongs to the same tenant, matches the current catalog version, and satisfies our cosine similarity threshold (>= 0.92) do we return the cached reply—in under 45 milliseconds and without invoking a generative model.

migrations/014_semantic_cache_pgvector.sqlsql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE semantic_cache (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id       UUID NOT NULL,
  catalog_version TEXT NOT NULL,
  intent_bucket   TEXT NOT NULL,
  normalized_text TEXT NOT NULL,
  embedding       vector(1536) NOT NULL,
  response_text   TEXT NOT NULL,
  hit_count       INTEGER NOT NULL DEFAULT 0,
  expires_at      TIMESTAMPTZ NOT NULL,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- HNSW index for fast cosine distance lookup
CREATE INDEX idx_semantic_cache_embedding
  ON semantic_cache
  USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

-- Composite index for tenant, version, and TTL scoping
CREATE INDEX idx_semantic_cache_scope
  ON semantic_cache (tenant_id, catalog_version, intent_bucket, expires_at);

Calibrating cosine similarity thresholds by intent bucket

Our first production mistake was relying on a single global cosine threshold across every question type. At 0.90, short queries such as 'how much is the red one?' and 'how much is the black one?' collided and served the wrong price. Raising the global threshold to 0.96 eliminated collisions but dropped our semantic hit rate below 8%, eroding the economic benefit.

Splitting thresholds by intent bucket solved the trade-off cleanly. General policy and shipping questions run safely at 0.92, whereas catalog queries carrying product attributes require 0.95 plus an exact match on extracted numeric tokens (sizes, model codes) and a minimum normalized length of 12 characters.

src/ai/cache/semantic-cache.service.tstypescript
import crypto from "node:crypto";
import type { Pool } from "pg";
import type { Redis } from "ioredis";

export interface CacheLookupInput {
  tenantId: string;
  catalogVersion: string;
  intentBucket: "policy" | "catalog" | "shipping";
  prompt: string;
}

const THRESHOLD_BY_INTENT: Record<CacheLookupInput["intentBucket"], number> = {
  policy: 0.92,
  shipping: 0.92,
  catalog: 0.95,
};

export function normalizePrompt(raw: string): string {
  return raw
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9\s]/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

export async function lookupSemanticCache(
  pg: Pool,
  redis: Redis,
  embed: (text: string) => Promise<number[]>,
  input: CacheLookupInput
): Promise<{ hit: "exact" | "semantic" | "miss"; answer?: string; similarity?: number }> {
  const normalized = normalizePrompt(input.prompt);
  if (normalized.length < 12) return { hit: "miss" };

  const exactHash = crypto
    .createHash("sha256")
    .update(`${input.tenantId}:${input.catalogVersion}:${normalized}`)
    .digest("hex");

  const exactHit = await redis.get(`llm:exact:${exactHash}`);
  if (exactHit) return { hit: "exact", answer: exactHit, similarity: 1 };

  const vector = await embed(normalized);
  const vectorLiteral = `[${vector.join(",")}]`;
  const minSimilarity = THRESHOLD_BY_INTENT[input.intentBucket];

  const { rows } = await pg.query<{ id: string; response_text: string; similarity: number }>(
    `SELECT id, response_text, 1 - (embedding <=> $1::vector) AS similarity
       FROM semantic_cache
      WHERE tenant_id = $2
        AND catalog_version = $3
        AND intent_bucket = $4
        AND expires_at > NOW()
      ORDER BY embedding <=> $1::vector
      LIMIT 1`,
    [vectorLiteral, input.tenantId, input.catalogVersion, input.intentBucket]
  );

  const best = rows[0];
  if (!best || best.similarity < minSimilarity) {
    return { hit: "miss" };
  }

  await pg.query("UPDATE semantic_cache SET hit_count = hit_count + 1 WHERE id = $1", [best.id]);
  return { hit: "semantic", answer: best.response_text, similarity: best.similarity };
}

Zero-downtime invalidation per tenant and catalog version

Stale cache entries destroy trust faster than slow responses. If a merchant updates a SKU price at 10:05 AM, no customer should receive the old price at 10:06 AM. Trying to delete individual vector rows by semantic proximity is slow and error-prone. Instead, every lookup binds an immutable `catalog_version` token—stored per tenant in Redis—into both the exact hash and the PostgreSQL filter clause.

Whenever the ingestion worker finishes updating a tenant's catalog, it atomically increments that tenant's `catalog_version`. New requests immediately stop matching stale rows with zero table locks, while an off-peak cleanup job batch-deletes expired rows so the HNSW index stays lean and predictable.

Latency benchmarks and how we measured the ~30% savings

To verify whether semantic caching paid for its operational footprint, we logged per-conversation telemetry across two consecutive two-week windows using the same codebase and product catalog. Window A ran with only the Redis exact cache enabled; Window B enabled both Redis exact caching and the pgvector semantic cache. We measured total billed tokens per multi-turn conversation rather than isolated requests.

Combining both layers cut billed tokens per conversation by ~30% while dramatically improving perceived responsiveness. Redis exact hits returned in ~6 ms and pgvector semantic hits (including embedding generation) completed in under 45 ms p95, compared to 1.4–2.8 seconds for a full LLM turn with tool execution. Meanwhile, embedding API costs remained under 2% of the generation spend avoided.

  • Redis exact cache hit: ~6 ms p95 latency, $0 generation cost.
  • pgvector semantic cache hit: ~42 ms p95 latency (embedding + HNSW scan).
  • Full LLM + tool-calling miss: 1.4s – 2.8s depending on provider load and context size.
  • Honest caveat: ~30% is a project benchmark under Atiende's catalog traffic profile; always instrument your own repetition rate before forecasting savings.

Production takeaways and next steps

Semantic caching is a force multiplier on top of disciplined prompt design and deterministic routing—never a substitute for them. If your team is shipping RAG pipelines or autonomous customer agents and wants predictable unit economics from day one, explore our Production AI Engineering, RAG Pipelines & Autonomous Agents service for full architectural details.

Next architectural step

Production AI Engineering, RAG Pipelines & Autonomous Agents

Want to apply this architecture in your stack? Reach out at info@artagdev.com.co or review the full deliverables of our dedicated service.