Skip to content

Redis Integration

Redis provides high-performance sliding-window rate limiting, generational query caching, ephemeral OTP storage, and background task queues for Kirak applications.

flowchart TD
A["Redis Server (KIRAK_REDIS_URL)"] --> B["<prefix>:rl:*<br/>(Sliding-Window Rate Limit Quotas)"]
A --> C["<prefix>:cache:*<br/>(Generational Query Cache)"]
A --> D["<prefix>:bl:*<br/>(Single-Use Nonces & Social Codes)"]
A --> E["<prefix>:otp:*<br/>(HMAC-Hashed SMS OTP Codes)"]
A --> G["<prefix>:tokens_valid_after:*<br/>(Per-User Access Token Revocation)"]
A --> F["<prefix>:ai:*<br/>(Conversation History & Approval Locks)"]
A --> G["<prefix>:jobs:*<br/>(Scheduler Queue Sorted Sets)"]

Install the Redis extra:

Terminal window
pip install "kirak[redis]"

Set the connection string in your environment:

KIRAK_REDIS_URL=redis://localhost:6379

Supported connection formats:

# Standard local connection
KIRAK_REDIS_URL=redis://localhost:6379
# Password authenticated
KIRAK_REDIS_URL=redis://:secret-password@localhost:6379
# Managed TLS connection (AWS ElastiCache, Upstash, Redis Cloud)
KIRAK_REDIS_URL=rediss://your-cluster-endpoint:6380
# Redis 6+ ACL user authentication
KIRAK_REDIS_URL=redis://app-user:secret-password@localhost:6379

To prevent collisions in shared Redis environments, Kirak prefixes all keys with redis.key_prefix (default: "kirak"):

{
"redis": {
"key_prefix": "app_staging"
}
}
  • Startup Ownership Verification: At startup, the runtime writes <prefix>:owner containing the application’s base_url. If a different application has already claimed that prefix, Kirak halts startup with a ConfigurationError to prevent cross-app data leakage.
  • Granular ACL Sandboxing: For multi-tenant Redis deployments, restrict each application’s Redis user to its explicit prefix:
    ACL SETUSER app_staging on >strong-password ~app_staging:* resetchannels -@all +ping +get +set +del +incr +expire +pttl +hset +hget +hgetall +sadd +srem +sismember +smembers +zadd +zcard +zrange +zrangebyscore +zrem +zremrangebyscore +eval +evalsha +multi +exec +discard

Component Behavior Without Redis Behavior With Redis
Rate Limiting Database fixed-window table (kirak_rate_limits) Sub-millisecond sliding-window sorted set via Lua scripts
One-Time Nonces Database table (auth_token_blacklist) Redis key with automatic TTL expiration (kirak:bl:*)
SMS OTP Storage Database table (auth_otp) Auto-expiring HMAC keys (kirak:otp:*)
Access Token Revocation None: access tokens are valid until they expire Per-user revocation time, expiring with the access token lifetime (kirak:tokens_valid_after:*)
API Key Caching Direct database lookup on every request 60-second key cache (kirak:apikey:*), purged on key revocation, account close, password reset and deactivation
Query Caching Disabled (every read hits database) Generational cache with automatic model mutation invalidation
AI Conversations Database rows Auto-expiring session keys (kirak:ai:conv:*)

Enable query caching globally in kirak.json:

{
"cache": {
"enabled": true,
"default_ttl_seconds": 60
}
}

Or configure it per model in models/posts.json:

{
"table": "posts",
"cache": {
"enabled": true,
"ttl_seconds": 300
}
}

Kirak uses generational invalidation rather than scanning or pattern-deleting keys:

kirak:cache:gen:{model} -> Integer generation counter
kirak:cache:q:{model}:{generation}:{sha256(sql+params)} -> Serialized query result
  • Because row-level security (RLS) SQL fragments are compiled into the query string before hashing, different users querying the same model automatically receive separate, isolated cache keys.
  • When any record is created, updated, or deleted, Kirak increments kirak:cache:gen:{model} in an atomic O(1) operation. All prior cached queries become instantly unreachable and expire naturally under their TTL.
  • GraphQL Transactional Safety: Mutations inside multi-root GraphQL transactions queue their cache invalidations and flush them only after the transaction commits successfully.

When KIRAK_REDIS_URL is configured but the Redis server becomes unreachable, Kirak maintains service availability through deliberate fail-open and fail-closed strategies:

Subsystem Failure Strategy Operational Behavior
One-Time Nonces & Codes Fail Closed Rejects token exchange requests (503 AUTH_UNAVAILABLE) to prevent replay attacks.
Access Token Revocation Fail Closed Requests carrying an access token get 503 AUTH_UNAVAILABLE until Redis answers.
API Key Verification Fail Open to DB Bypasses the cache and queries the database table directly.
Rate Limiting Fail Open to DB Requests are counted in the database. If the database cannot count either, auth routes refuse with 503 AUTH_UNAVAILABLE and other routes are allowed through.
Query Caching Fail Open to DB Queries bypass the cache and execute directly against SQL connections.
SMS OTP Verification Fail Open to DB Codes are persisted and verified using the auth_otp SQL table.

Connection attempts time out after 1 second, and Kirak pauses connection retries for 5 seconds following a failure, preventing request threads from blocking.