Skip to content

Cache Management API

Base path: /api/v1/cache

Implementation reference: internal/cache/handler.go, service in internal/cache/service.go.

The cache system stores Prometheus query results to reduce latency and load on Prometheus data sources. It supports a two-tier architecture: an in-memory sync.Map for hot entries and a database-backed persistent store.

Endpoints

MethodPathDescriptionAuth Required
GET/cache/statisticsGet cache performance statisticsYes
POST/cache/invalidateInvalidate cache entries by key, SLO, pattern, expired, or allYes
POST/cache/warmupPreload cache with specified queriesYes
GET/cache/configGet current cache configurationYes
PUT/cache/configUpdate cache configurationYes
GET/cache/entry/:keyGet a specific cache entry by keyYes
POST/cache/entryManually create a cache entryYes
GET/cache/entriesList cache entries with filteringYes
DELETE/cache/entry/:keyDelete a specific cache entryYes

Routes are registered via internal/cache/handler.go:345 (RegisterRoutes).


GET /cache/statistics

Returns cache performance metrics including hit rate, memory usage, and entry counts.

Response (200 OK):

json
{
  "success": true,
  "data": {
    "total_entries": 1250,
    "total_hits": 15000,
    "total_misses": 3500,
    "hit_rate": 0.81,
    "average_ttl": 300,
    "average_entry_size": 2048,
    "memory_usage_mb": 2.5,
    "is_fresh_count": 1100,
    "expired_count": 150,
    "hot_entries_count": 300,
    "cold_entries_count": 950
  }
}

Statistics are tracked in-memory (CacheStatistics in internal/cache/service.go:44) and aggregated with database-level stats.


POST /cache/invalidate

Invalidates cache entries based on the specified type. Supports five invalidation strategies:

Request (by exact key):

json
{
  "type": "key",
  "key": "query:1:24h:abc123..."
}

Request (by SLO ID — invalidates all entries for an SLO):

json
{
  "type": "slo",
  "slo_id": 1
}

Request (by key pattern — prefix match):

json
{
  "type": "pattern",
  "pattern": "query:1:"
}

Request (expired entries — cleanup stale data):

json
{
  "type": "expired"
}

Request (all cache — full flush):

json
{
  "type": "all"
}

Response (200 OK):

json
{
  "success": true,
  "message": "Cache invalidated successfully",
  "data": {
    "type": "slo",
    "invalidations": 15,
    "timestamp": "2026-06-11T10:00:00Z"
  }
}

POST /cache/warmup

Pre-populates the cache by executing and storing results for specified Prometheus queries. Useful after deployment or configuration changes.

Request:

json
{
  "queries": [
    {
      "query": "rate(http_requests_total{job=\"api\"}[5m])",
      "slo_id": 1,
      "time_window": "24h",
      "ttl": 300000000000
    },
    {
      "query": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))",
      "slo_id": 2,
      "time_window": "1h",
      "ttl": 600000000000
    }
  ]
}
FieldTypeDescription
querystringPromQL query string
slo_idintSLO ID this query belongs to
time_windowstringTime window (e.g. 24h, 7d)
ttlintTTL in nanoseconds (defaults to 5 minutes)

Response (200 OK):

json
{
  "success": true,
  "message": "Cache warmed up successfully",
  "data": {
    "queries_warmed": 2,
    "timestamp": "2026-06-11T10:00:00Z"
  }
}

GET /cache/config

Returns the current cache configuration.

Response (200 OK):

json
{
  "success": true,
  "data": {
    "default_ttl": 300000000000,
    "max_entries": 10000,
    "cleanup_interval": 3600000000000,
    "enable_memory_cache": true,
    "enable_compression": true,
    "compression_threshold": 1024,
    "enable_warmup": true,
    "analytics_retention": 2592000000000000
  }
}

Configuration fields and their types (from internal/cache/service.go:69):

FieldTypeDescription
default_ttldurationDefault TTL for cached entries
max_entriesintMaximum number of cache entries before eviction
cleanup_intervaldurationHow often expired entries are cleaned up
enable_memory_cacheboolEnable in-memory cache tier
enable_compressionboolCompress large cache entries with gzip
compression_thresholdintMinimum entry size (bytes) for compression
enable_warmupboolAllow cache warmup operations
analytics_retentiondurationHow long to retain cache analytics

PUT /cache/config

Updates cache configuration at runtime. Only provided fields are updated.

Request:

json
{
  "default_ttl": 600000000000,
  "max_entries": 20000,
  "enable_compression": false
}

Response (200 OK):

json
{
  "success": true,
  "message": "Cache configuration updated successfully"
}

GET /cache/entry/:key

Retrieves a specific cache entry by its key. The key is URL-encoded in the path.

Response (200 OK):

json
{
  "success": true,
  "data": {
    "key": "query:1:24h:abc123...",
    "query_hash": "xyz789...",
    "query": "rate(http_requests_total[5m])",
    "slo_id": 1,
    "time_window": "24h",
    "result": {
      "current_value": 0.998,
      "target_value": 0.995,
      "status": "healthy"
    },
    "cached_at": "2026-06-11T09:30:00Z",
    "expires_at": "2026-06-11T09:35:00Z",
    "hit_count": 250,
    "last_hit": "2026-06-11T09:34:55Z",
    "is_fresh": true
  }
}

Cache entry fields (from internal/cache/service.go:14):

FieldDescription
keyUnique cache key (query:{slo_id}:{time_window}:{hash})
query_hashSHA-256 hash of the query
queryOriginal PromQL query string
slo_idAssociated SLO ID
resultCached query result data
cached_atWhen the entry was cached
expires_atWhen the entry expires
hit_countNumber of cache hits
is_freshWhether the entry is still fresh

POST /cache/entry

Manually creates a cache entry. Useful for testing or pre-populating specific values.

Request:

json
{
  "key": "manual:entry:1",
  "query": "up{job=\"api\"}",
  "slo_id": 1,
  "time_window": "5m",
  "result": {
    "value": 1
  },
  "ttl": 120000000000
}
FieldTypeRequiredDescription
keystringYesCache key
querystringYesPromQL query
slo_idintYesSLO ID
time_windowstringYesTime window
resultanyYesResult data to cache
ttldurationNoTTL in nanoseconds (default: 5 minutes)

Response (200 OK):

json
{
  "success": true,
  "message": "Cache entry created successfully"
}

GET /cache/entries

Lists cache entries with optional filtering and pagination.

Query Parameters:

ParameterTypeDefaultDescription
pageint1Page number
page_sizeint20Items per page (max 100)
slo_idintFilter by SLO ID
freshboolFilter by fresh/expired status

Response (200 OK):

json
{
  "success": true,
  "data": {
    "entries": [
      {
        "key": "query:1:24h:abc123...",
        "query": "rate(http_requests_total[5m])",
        "slo_id": 1,
        "time_window": "24h",
        "cached_at": "2026-06-11T09:30:00Z",
        "expires_at": "2026-06-11T09:35:00Z",
        "hit_count": 250,
        "is_fresh": true
      }
    ],
    "total": 1250,
    "page": 1,
    "page_size": 20,
    "has_next": true
  }
}

DELETE /cache/entry/:key

Deletes a specific cache entry by its key.

Response (200 OK):

json
{
  "success": true,
  "message": "Cache entry deleted successfully"
}

Cache Eviction

When max_entries is reached, the cache evicts the least recently used (LRU) entry (internal/cache/service.go:365).

Background Cleanup

A background goroutine runs periodically (cleanupInterval) to delete expired entries from the database (internal/cache/service.go:343).

Error Codes

HTTP StatusScenario
400Invalid request body, missing required fields
404Cache entry not found
500Database error, service failure