Skip to content

Semantic Caching

Semantic caching uses vector similarity search to intelligently cache AI responses, serving cached results for semantically similar requests even when the exact wording differs. This dramatically reduces API costs and latency for repeated or similar queries.

Key Benefits:

  • Cost Reduction: Avoid expensive LLM API calls for similar requests
  • Improved Performance: Sub-millisecond cache retrieval vs multi-second API calls
  • Intelligent Matching: Semantic similarity beyond exact text matching
  • Streaming Support: Full streaming response caching with proper chunk ordering

  • Dual-Layer Caching: Exact hash matching + semantic similarity search (customizable threshold)
  • Vector-Powered Intelligence: Uses embeddings to find semantically similar requests
  • Dynamic Configuration: Per-request TTL and threshold overrides via headers/context
  • Model/Provider Isolation: Separate caching per model and provider combination

Semantic caching requires a configured vector store. DeepIntShield supports the following vector databases:

  • Weaviate: Production-ready vector database with gRPC support
  • Redis: High-performance in-memory vector store using RediSearch-compatible APIs (including Valkey bundles with FT.* support)
  • Qdrant: Rust-based vector search engine with advanced filtering
  • Pinecone: Managed vector database service with serverless options

Quick Example (Weaviate):

import (
"context"
"github.com/maximhq/deepintshield/framework/vectorstore"
)
// Configure vector store (example: Weaviate)
vectorConfig := &vectorstore.Config{
Enabled: true,
Type: vectorstore.VectorStoreTypeWeaviate,
Config: vectorstore.WeaviateConfig{
Scheme: "http",
Host: "localhost:8080",
},
}
// Create vector store
store, err := vectorstore.NewVectorStore(context.Background(), vectorConfig, logger)
if err != nil {
log.Fatal("Failed to create vector store:", err)
}

import (
"github.com/maximhq/deepintshield/plugins/semanticcache"
"github.com/maximhq/deepintshield/core/schemas"
)
// Configure semantic cache plugin
cacheConfig := &semanticcache.Config{
// Embedding model configuration (Required)
Provider: schemas.OpenAI,
Keys: []schemas.Key{{Value: "sk-..."}},
EmbeddingModel: "text-embedding-3-small",
Dimension: 1536,
// Cache behavior
TTL: 5 * time.Minute, // Time to live for cached responses (default: 5 minutes)
Threshold: 0.8, // Similarity threshold for cache lookup (default: 0.8)
CleanUpOnShutdown: true, // Clean up cache on shutdown (default: false)
// Conversation behavior
ConversationHistoryThreshold: 5, // Skip caching if conversation has > N messages (default: 3)
ExcludeSystemPrompt: deepintshield.Ptr(false), // Exclude system messages from cache key (default: false)
// Advanced options
CacheByModel: deepintshield.Ptr(true), // Include model in cache key (default: true)
CacheByProvider: deepintshield.Ptr(true), // Include provider in cache key (default: true)
}
// Create plugin
plugin, err := semanticcache.Init(context.Background(), cacheConfig, logger, store)
if err != nil {
log.Fatal("Failed to create semantic cache plugin:", err)
}
// Add to DeepIntShield config
bifrostConfig := schemas.DeepIntShieldConfig{
LLMPlugins: []schemas.LLMPlugin{plugin},
// ... other config
}

Direct hash mode provides exact-match caching without requiring an embedding provider. Each request is hashed deterministically based on its normalized input, parameters, and stream flag. Identical requests produce cache hits; different wording is a cache miss.

When to use direct hash mode:

  • You only need exact-match deduplication (no fuzzy/semantic matching)
  • You cannot or do not want to call an external embedding API
  • You want the lowest possible latency with zero embedding overhead
  • Cost-sensitive environments where embedding API calls add up

To enable direct-only mode globally, omit the provider and keys fields from the plugin config. The plugin will automatically fall back to direct search only.

import (
"github.com/maximhq/deepintshield/plugins/semanticcache"
)
cacheConfig := &semanticcache.Config{
// No Provider, Keys, or EmbeddingModel -- direct hash mode only
Dimension: 1, // Placeholder; entries are stored as metadata-only (no embedding vectors). Change dimension before switching to dual-layer mode to avoid mixed-dimension issues.
TTL: 5 * time.Minute,
CleanUpOnShutdown: true,
CacheByModel: deepintshield.Ptr(true),
CacheByProvider: deepintshield.Ptr(true),
}
plugin, err := semanticcache.Init(ctx, cacheConfig, logger, store)

When initialized this way, all requests automatically use direct hash matching regardless of the x-bf-cache-type header. No embeddings are generated, and no embedding provider credentials are needed.

Redis/Valkey-compatible stores are recommended for direct hash mode. They do not require vectors for metadata-only entries, and all cache fields are indexed as TAG fields for fast exact-match lookups.

vectorStore:
enabled: true
type: redis
redis:
external:
enabled: true
host: "redis-or-valkey.example.com"
port: 6379
password: "your-redis-password"

When the plugin is initialized without an embedding provider (direct-only mode), all requests use direct hash matching automatically. The x-bf-cache-type header has no effect.

When the plugin is initialized with an embedding provider (dual-layer mode), you can force direct-only matching on specific requests using the x-bf-cache-type: direct header. See Cache Type Control for details.


Must set cache key in request context:

// This request WILL be cached
ctx = context.WithValue(ctx, semanticcache.CacheKey, "session-123")
response, err := client.ChatCompletionRequest(schemas.NewDeepIntShieldContext(ctx, schemas.NoDeadline), request)
// This request will NOT be cached (no context value)
response, err := client.ChatCompletionRequest(schemas.NewDeepIntShieldContext(context.Background(), schemas.NoDeadline), request)

Workspace-level settings (configured under Governance Hub → Cost Optimization) are the default for every request. Any individual call can override them by sending one of the following headers — useful for batch jobs that need a longer TTL, evals that should bypass the cache, or hot paths that want a stricter similarity threshold.

HeaderEffect
x-bf-cache-ttlOverride the semantic cache TTL for this request (e.g. 30s, 5m, 3600).
x-bf-cache-thresholdOverride the similarity threshold for this request (0.01.0).
x-bf-cache-typeForce a specific cache type for this request: direct or semantic.
x-bf-cache-no-storeSet to true to read from the cache but not write the new response back.
x-bf-cache-keyProvide an explicit cache key for direct hash matching (skips semantic lookup).

Override default TTL and similarity threshold per request:

You can set TTL and threshold in the request context, in the keys you configured in the plugin config:

// Go SDK: Custom TTL and threshold
ctx = context.WithValue(ctx, semanticcache.CacheKey, "session-123")
ctx = context.WithValue(ctx, semanticcache.CacheTTLKey, 30*time.Second)
ctx = context.WithValue(ctx, semanticcache.CacheThresholdKey, 0.9)

Control which caching mechanism to use per request:

// Use only direct hash matching (fastest)
ctx = context.WithValue(ctx, semanticcache.CacheKey, "session-123")
ctx = context.WithValue(ctx, semanticcache.CacheTypeKey, semanticcache.CacheTypeDirect)
// Use only semantic similarity search
ctx = context.WithValue(ctx, semanticcache.CacheKey, "session-123")
ctx = context.WithValue(ctx, semanticcache.CacheTypeKey, semanticcache.CacheTypeSemantic)
// Default behavior: Direct + semantic fallback (if not specified)
ctx = context.WithValue(ctx, semanticcache.CacheKey, "session-123")

Disable response caching while still allowing cache reads:

// Read from cache but don't store the response
ctx = context.WithValue(ctx, semanticcache.CacheKey, "session-123")
ctx = context.WithValue(ctx, semanticcache.CacheNoStoreKey, true)

The ConversationHistoryThreshold setting skips caching for conversations with many messages to prevent false positives:

Why this matters:

  • Semantic False Positives: Long conversation histories have high probability of semantic matches with unrelated conversations due to topic overlap
  • Direct Cache Inefficiency: Long conversations rarely have exact hash matches, making direct caching less effective
  • Performance: Reduces vector store load by filtering out low-value caching scenarios
{
"conversation_history_threshold": 3 // Skip caching if > 3 messages in conversation
}

Recommended Values:

  • 1-2: Very conservative (may miss valuable caching opportunities)
  • 3-5: Balanced approach (default: 3)
  • 10+: Cache longer conversations (higher false positive risk)

Control whether system messages are included in cache key generation:

{
"exclude_system_prompt": false // Include system messages in cache key (default)
}

When to exclude (true):

  • System prompts change frequently but content is similar
  • Multiple system prompt variations for same use case
  • Focus caching on user content similarity

When to include (false):

  • System prompts significantly change response behavior
  • Each system prompt requires distinct cached responses
  • Strict response consistency requirements

When responses are served from semantic cache, 3 key variables are automatically added to the response:

Location: response.ExtraFields.CacheDebug (as a JSON object)

Fields:

  • CacheHit (boolean): true if the response was served from the cache, false when lookup fails.
  • HitType (string): "semantic" for similarity match, "direct" for hash match
  • CacheID (string): Unique cache entry ID for management operations (present only for cache hits)

Semantic Cache Only:

  • ProviderUsed (string): Provider used for the calculating semantic match embedding. (present for both cache hits and misses)
  • ModelUsed (string): Model used for the calculating semantic match embedding. (present for both cache hits and misses)
  • InputTokens (number): Number of tokens extracted from the request for the semantic match embedding calculation. (present for both cache hits and misses)
  • Threshold (number): Similarity threshold used for the match. (present only for cache hits)
  • Similarity (number): Similarity score for the match. (present only for cache hits)

Example HTTP Response:

{
"extra_fields": {
"cache_debug": {
"cache_hit": true,
"hit_type": "direct",
"cache_id": "550e8500-e29b-41d4-a725-446655440001",
}
}
}
{
"extra_fields": {
"cache_debug": {
"cache_hit": true,
"hit_type": "semantic",
"cache_id": "550e8500-e29b-41d4-a725-446655440001",
"threshold": 0.8,
"similarity": 0.95,
"provider_used": "openai",
"model_used": "gpt-4o-mini",
"input_tokens": 100
}
}
}
{
"extra_fields": {
"cache_debug": {
"cache_hit": false,
"provider_used": "openai",
"model_used": "gpt-4o-mini",
"input_tokens": 20
}
}
}

These variables allow you to detect cached responses and get the cache entry ID needed for clearing specific entries.

Use the request ID from cached responses to clear specific entries:

// Clear specific entry by request ID
err := plugin.ClearCacheForRequestID("550e8400-e29b-41d4-a716-446655440000")
// Clear all entries for a cache key
err := plugin.ClearCacheForKey("support-session-456")

The semantic cache automatically handles cleanup to prevent storage bloat:

Automatic Cleanup:

  • TTL Expiration: Entries are automatically removed when TTL expires
  • Shutdown Cleanup: All cache entries are cleared from the vector store namespace and the namespace itself when DeepIntShield client shuts down
  • Namespace Isolation: Each DeepIntShield instance uses isolated vector store namespaces to prevent conflicts

Manual Cleanup Options:

  • Clear specific entries by request ID (see examples above)
  • Clear all entries for a cache key
  • Restart DeepIntShield to clear all cache data