Skip to content

Cache Options

Caching configuration for PostgreSQL routines that return single result sets.

Overview

json
{
  "CacheOptions": {
    "Enabled": false,
    "Type": "Memory",
    "MemoryCachePruneIntervalSeconds": 60,
    "RedisConfiguration": "localhost:6379,abortConnect=false,ssl=false,connectTimeout=10000,syncTimeout=5000,connectRetry=3"
  }
}

Settings Reference

SettingTypeDefaultDescription
EnabledboolfalseEnable caching for routines.
Typestring"Memory"Cache type: "Memory" or "Redis".
MemoryCachePruneIntervalSecondsint60How often to prune expired items from memory cache (in seconds).
RedisConfigurationstring(see below)Redis connection string. Only used when Type is "Redis".

Cache Types

Memory Cache

In-memory caching on the application server:

json
{
  "CacheOptions": {
    "Enabled": true,
    "Type": "Memory",
    "MemoryCachePruneIntervalSeconds": 60
  }
}

The MemoryCachePruneIntervalSeconds setting controls how frequently expired cache entries are removed.

Redis Cache

Distributed caching using Redis:

json
{
  "CacheOptions": {
    "Enabled": true,
    "Type": "Redis",
    "RedisConfiguration": "localhost:6379,abortConnect=false,ssl=false,connectTimeout=10000,syncTimeout=5000,connectRetry=3"
  }
}

See StackExchange.Redis Configuration for connection string options.

Routine Annotations

Enable caching for specific routines using comment annotations:

cached

Mark a routine as cacheable:

sql
comment on function get_products() is '
HTTP GET /products
cached
';

Specify which parameters to use for the cache key:

sql
comment on function get_product(p_id int) is '
HTTP GET /products/{p_id}
cached p_id
';

If no parameters are specified, all parameters are used for the cache key.

cache_expires / cache_expires_in

Set cache expiration using PostgreSQL interval format:

sql
comment on function get_products() is '
HTTP GET /products
cached
cache_expires 5 minutes
';
sql
comment on function get_config() is '
HTTP GET /config
cached
cache_expires_in 1 hour
';

Supported interval formats:

  • 5 minutes or 5min
  • 1 hour or 1h
  • 30 seconds or 30s
  • 1 day or 1d

If no expiration is specified, cache entries never expire.

Limitations

WARNING

Only routines that return a single result set can be cached. Routines returning tables (RETURNS TABLE) or sets (RETURNS SETOF) cannot be cached.

Example Configuration

Production configuration with Redis:

json
{
  "CacheOptions": {
    "Enabled": true,
    "Type": "Redis",
    "RedisConfiguration": "redis-server:6379,password={REDIS_PASSWORD},ssl=true,abortConnect=false"
  }
}

Development configuration with memory cache:

json
{
  "CacheOptions": {
    "Enabled": true,
    "Type": "Memory",
    "MemoryCachePruneIntervalSeconds": 30
  }
}

Next Steps

Released under the MIT License.