# AI-Trader Redis Cache Configuration: Understanding REDIS_ENABLED and Connection Settings

> Configure Redis cache in AI-Trader with REDIS_ENABLED and connection settings. Learn how to enable caching and set your Redis URL and key prefix for HKUDS/AI-Trader.

- Repository: [✨Data Intelligence Lab@HKU✨/AI-Trader](https://github.com/HKUDS/AI-Trader)
- Tags: configuration
- Published: 2026-05-09

---

**The `REDIS_ENABLED` environment variable toggles the Redis cache in HKUDS/AI-Trader, accepting case-insensitive values `1`, `true`, `yes`, or `on` to enable caching, while `REDIS_URL` provides the connection string and `REDIS_PREFIX` sets the key namespace.**

The HKUDS/AI-Trader repository implements a lightweight caching layer built around Redis to support high-frequency trading operations and distributed coordination. All Redis cache configuration options are defined in [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py) and consumed by [`service/server/cache.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/cache.py), allowing the service to boot and run gracefully even when Redis is unavailable. Proper configuration of these environment variables ensures optimal performance without risking runtime connection failures.

## Core Redis Cache Configuration Options

Three environment variables control the Redis integration. These are loaded at startup from the project root `.env` file and exposed as module-level constants.

### REDIS_ENABLED Toggle

The **`REDIS_ENABLED`** setting acts as the master switch for the entire caching subsystem. According to [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py) at line 22, the value is interpreted as a boolean where the following case-insensitive strings activate the cache: `1`, `true`, `yes`, or `on`. Any other value or absence of the variable defaults to `false`, keeping the cache disabled.

### REDIS_URL Connection String

**`REDIS_URL`** defines the server connection endpoint (e.g., `redis://localhost:6379/0`). Defined at line 23 of [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py), this variable defaults to an empty string. If `REDIS_URL` is missing or empty, the cache layer considers Redis *not configured* even when `REDIS_ENABLED` is set to true, triggering graceful fallback behavior.

### REDIS_PREFIX Key Namespace

The **`REDIS_PREFIX`** setting (line 24 in [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py)) prepends a namespace to every key stored in Redis, defaulting to `"ai_trader"`. This prevents key collisions when multiple services share the same Redis instance. The cache module uses the internal `_namespaced(key)` helper to automatically apply this prefix.

## Configuration Validation and Runtime Checks

The actual availability of Redis depends on more than just the environment variables. The `redis_configured()` helper function in [`service/server/cache.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/cache.py) (lines 36-38) enforces a strict validation rule: it returns `True` only when **`REDIS_ENABLED` is `True` AND `REDIS_URL` is non-empty**.

The `get_redis_client()` function respects this validation, returning `None` when the cache is disabled. All high-level operations (`get_json`, `set_json`, `delete`) check for this `None` client and execute as no-ops rather than raising exceptions, ensuring the trading service remains operational without a Redis server.

## Environment Configuration Example

Create or modify the `.env` file in the project root to enable and configure the cache:

```dotenv
REDIS_ENABLED=true
REDIS_URL=redis://localhost:6379/0
REDIS_PREFIX=ai_trader

```

When these values are present, the cache layer initializes a `redis.Redis` client lazily upon first use. If any variable is omitted or invalid, the service continues with caching disabled.

## Runtime Cache Inspection and Operations

### Checking Cache Health

Use `get_cache_status()` (implemented in [`service/server/cache.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/cache.py) lines 74-83) to verify the current cache state programmatically:

```python
from service.server.cache import get_cache_status

status = get_cache_status()
print(status)

```

This returns a dictionary containing:

- `enabled`: Whether `REDIS_ENABLED` is true
- `configured`: Whether both `REDIS_ENABLED` and `REDIS_URL` are valid
- `available`: Whether the Redis server is actually reachable
- `prefix`: The current `REDIS_PREFIX` value
- `last_error`: Any connection error encountered during the last health check

### Storing and Retrieving JSON Data

The cache module provides convenience methods for JSON serialization:

```python
from service.server.cache import set_json, get_json

# Store with TTL of 3600 seconds

set_json("portfolio:user_123", {"stocks": ["AAPL", "TSLA"], "cash": 5000}, ttl_seconds=3600)

# Retrieve later

data = get_json("portfolio:user_123")

```

### Distributed Locking

For coordinating tasks across multiple AI-Trader workers, use the lock acquisition helper:

```python
from service.server.cache import acquire_lock

lock = acquire_lock("market_data_sync", timeout_seconds=30, blocking=True)
if lock:
    with lock:
        # Critical section: only one worker executes this at a time

        update_market_data()
else:
    print("Failed to acquire distributed lock")

```

## Summary

- **`REDIS_ENABLED`** controls the cache toggle and accepts `1`, `true`, `yes`, or `on` (case-insensitive) to activate the feature in [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py).
- **`REDIS_URL`** must be a valid connection string; an empty value disables caching even when enabled.
- **`REDIS_PREFIX`** isolates keys with a namespace defaulting to `"ai_trader"`.
- The `redis_configured()` helper in [`service/server/cache.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/cache.py) requires both the toggle and URL to be set before initializing the client.
- All cache operations degrade gracefully to no-ops when Redis is unavailable, ensuring uninterrupted service operation.
- Use `get_cache_status()` to verify runtime connectivity and configuration health.

## Frequently Asked Questions

### What exact values activate the REDIS_ENABLED setting?

The `REDIS_ENABLED` variable accepts case-insensitive strings `1`, `true`, `yes`, or `on` to evaluate as boolean true. Any other value, including the absence of the variable, defaults to false and keeps the cache disabled according to the parser in [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py) line 22.

### What happens if REDIS_URL is empty but REDIS_ENABLED is true?

The cache remains effectively disabled. The `redis_configured()` function in [`service/server/cache.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/cache.py) (lines 36-38) requires both conditions to be met: `REDIS_ENABLED` must be true AND `REDIS_URL` must be non-empty. When the URL is missing, `get_redis_client()` returns `None` and all cache operations fall back to no-op behavior without raising errors.

### How can I verify if the Redis cache is actually connected and working?

Call `get_cache_status()` from [`service/server/cache.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/cache.py). This function attempts a live connection to Redis and returns a dictionary indicating whether the cache is enabled, correctly configured, and currently available, along with the configured prefix and any recent connection errors captured at lines 74-83.

### Can multiple AI-Trader instances share the same Redis server safely?

Yes, provided each instance uses a unique **`REDIS_PREFIX`** or they intentionally share the namespace for distributed coordination. The prefix is prepended to every key via the internal `_namespaced()` helper, preventing accidental collisions between different services or environments using the same Redis instance.