class

Ralph::Query::QueryCache

Inherits Reference / Object

Thread-safe query result cache with TTL and LRU eviction

This cache stores query results and provides:

  • Time-to-live (TTL) for automatic expiration
  • LRU (Least Recently Used) eviction when max size is reached
  • Thread-safe access via mutex
  • Table-based invalidation for write operations
  • Cache statistics for monitoring

Example

cache = Ralph::Query::QueryCache.new(max_size: 1000, default_ttl: 5.minutes)

# Store a result
cache.set("query_key", results)

# Retrieve a result (returns nil if expired or not found)
if result = cache.get("query_key")
  # Use cached result
end

# Invalidate all entries for a table
cache.invalidate_table("users")

# Get cache statistics
stats = cache.stats
puts "Hits: #{stats[:hits]}, Misses: #{stats[:misses]}"

Constructors

new(max_size : Int32 = 1000, default_ttl : Time::Span = 5.minutes, enabled : Bool = true)

Create a new query cache

Parameters

  • max_size: Maximum number of entries before LRU eviction (default: 1000)
  • default_ttl: Default time-to-live for entries (default: 5 minutes)
  • enabled: Whether caching is enabled (default: true)
Source

Instance methods

clear

Clear all cached entries

Source
default_ttl

Get the default TTL

Source
delete(key : String) : Nil

Delete a specific cache entry

Source
disable

Disable the cache (clears all entries)

Source
enable

Enable the cache

Source
enabled?

Check if caching is enabled

Source
get(key : String) : Array(Hash(String, DBValue)) | Nil

Get a cached result by key

Returns nil if not found, expired, or cache is disabled. Automatically removes expired entries.

Source
has_key?(key : String) : Bool

Check if a key exists and is not expired

Source
invalidate_table(table : String) : Int32

Invalidate all cache entries that reference a specific table

This should be called after INSERT, UPDATE, or DELETE operations to ensure cached results don't return stale data.

Source
max_size

Get the maximum cache size

Source
prune_expired

Prune expired entries

This can be called periodically to clean up expired entries that haven't been accessed. Returns the number of entries removed.

Source
reset_stats

Reset statistics (keeps cache entries)

Source
set(key : String, data : Array(Hash(String, DBValue)), ttl : Time::Span | Nil = nil) : Nil

Store a result in the cache

If the cache is at max capacity, evicts the least recently used entry.

Source
size

Get the current cache size

Source
stats

Get cache statistics

Source

Nested types