|
| 1 | +# Redis Cache Plugin for Bifrost |
| 2 | + |
| 3 | +This plugin provides Redis-based caching functionality for Bifrost requests. It caches responses based on request body hashes and returns cached responses for identical requests, significantly improving performance and reducing API costs. |
| 4 | + |
| 5 | +## Features |
| 6 | + |
| 7 | +- **Request Body Hashing**: Uses SHA256 to generate consistent hashes from request bodies |
| 8 | +- **Response Caching**: Stores complete responses in Redis with configurable TTL |
| 9 | +- **Cache Hit Detection**: Returns cached responses for identical requests |
| 10 | +- **Cache Management**: Provides utilities to clear cache and get cache information |
| 11 | +- **Configurable**: Supports custom Redis connection settings, TTL, and key prefixes |
| 12 | + |
| 13 | +## Installation |
| 14 | + |
| 15 | +```bash |
| 16 | +go get github.com/redis/go-redis/v9 |
| 17 | +go get github.com/maximhq/bifrost/core |
| 18 | +``` |
| 19 | + |
| 20 | +## Usage |
| 21 | + |
| 22 | +### Basic Setup |
| 23 | + |
| 24 | +```go |
| 25 | +import ( |
| 26 | + "github.com/maximhq/bifrost/plugins/redis" |
| 27 | + "time" |
| 28 | +) |
| 29 | + |
| 30 | +// Configure the Redis plugin |
| 31 | +config := redis.RedisPluginConfig{ |
| 32 | + RedisAddr: "localhost:6379", // Redis server address |
| 33 | + RedisPassword: "", // Redis password (if required) |
| 34 | + RedisDB: 0, // Redis database number |
| 35 | + TTL: 24 * time.Hour, // Cache TTL (24 hours) |
| 36 | + Prefix: "bifrost:cache:", // Cache key prefix |
| 37 | +} |
| 38 | + |
| 39 | +// Create the plugin |
| 40 | +plugin, err := redis.NewRedisPlugin(config) |
| 41 | +if err != nil { |
| 42 | + log.Fatal("Failed to create Redis plugin:", err) |
| 43 | +} |
| 44 | + |
| 45 | +// Use with Bifrost |
| 46 | +bifrostConfig := schemas.BifrostConfig{ |
| 47 | + Account: yourAccount, |
| 48 | + Plugins: []schemas.Plugin{plugin}, |
| 49 | + // ... other config |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +### Configuration Options |
| 54 | + |
| 55 | +| Option | Type | Default | Description | |
| 56 | +| --------------- | --------------- | ------------------ | --------------------------------- | |
| 57 | +| `RedisAddr` | `string` | `"localhost:6379"` | Redis server address | |
| 58 | +| `RedisPassword` | `string` | `""` | Redis password (empty if no auth) | |
| 59 | +| `RedisDB` | `int` | `0` | Redis database number | |
| 60 | +| `TTL` | `time.Duration` | `24 * time.Hour` | Time-to-live for cached responses | |
| 61 | +| `Prefix` | `string` | `"bifrost:cache:"` | Prefix for cache keys | |
| 62 | + |
| 63 | +### Advanced Usage |
| 64 | + |
| 65 | +#### Cache Management |
| 66 | + |
| 67 | +```go |
| 68 | +// Get cache information |
| 69 | +info, err := plugin.(*redis.Plugin).GetCacheInfo(ctx) |
| 70 | +if err != nil { |
| 71 | + log.Printf("Cache info: %+v", info) |
| 72 | +} |
| 73 | + |
| 74 | +// Clear all cached entries |
| 75 | +err = plugin.(*redis.Plugin).ClearCache(ctx) |
| 76 | +if err != nil { |
| 77 | + log.Printf("Failed to clear cache: %v", err) |
| 78 | +} |
| 79 | + |
| 80 | +// Close Redis connection when done |
| 81 | +defer plugin.(*redis.Plugin).Close() |
| 82 | +``` |
| 83 | + |
| 84 | +## How It Works |
| 85 | + |
| 86 | +### Request Hashing |
| 87 | + |
| 88 | +The plugin generates a SHA256 hash of the normalized request including: |
| 89 | + |
| 90 | +- Provider |
| 91 | +- Model |
| 92 | +- Input (chat completion or text completion) |
| 93 | +- Parameters |
| 94 | +- Fallbacks |
| 95 | + |
| 96 | +Identical requests will always produce the same hash, enabling effective caching. |
| 97 | + |
| 98 | +### Caching Flow |
| 99 | + |
| 100 | +1. **PreHook**: |
| 101 | + |
| 102 | + - Generates hash from incoming request |
| 103 | + - Checks Redis for cached response |
| 104 | + - If found, returns cached response (skips provider call) |
| 105 | + - If not found, stores hash in context for PostHook |
| 106 | + |
| 107 | +2. **PostHook**: |
| 108 | + - Retrieves hash from context |
| 109 | + - Stores the response in Redis with the hash as key |
| 110 | + - Sets TTL on the cached entry |
| 111 | + |
| 112 | +### Cache Keys |
| 113 | + |
| 114 | +Cache keys follow the pattern: `{prefix}{sha256_hash}` |
| 115 | + |
| 116 | +Example: `bifrost:cache:a1b2c3d4e5f6...` |
| 117 | + |
| 118 | +## Testing |
| 119 | + |
| 120 | +Run the tests with a Redis instance running: |
| 121 | + |
| 122 | +```bash |
| 123 | +# Start Redis (using Docker) |
| 124 | +docker run -d -p 6379:6379 redis:latest |
| 125 | + |
| 126 | +# Run tests |
| 127 | +go test ./... |
| 128 | +``` |
| 129 | + |
| 130 | +Tests will be skipped if Redis is not available. |
| 131 | + |
| 132 | +## Performance Benefits |
| 133 | + |
| 134 | +- **Reduced API Calls**: Identical requests are served from cache |
| 135 | +- **Lower Latency**: Cache hits return immediately without network calls |
| 136 | +- **Cost Savings**: Fewer API calls to expensive LLM providers |
| 137 | +- **Improved Reliability**: Cached responses available even if provider is down |
| 138 | + |
| 139 | +## Error Handling |
| 140 | + |
| 141 | +The plugin is designed to fail gracefully: |
| 142 | + |
| 143 | +- If Redis is unavailable, requests continue without caching |
| 144 | +- If cache retrieval fails, requests proceed normally |
| 145 | +- If cache storage fails, responses are returned without caching |
| 146 | +- Malformed cached data is ignored and requests proceed normally |
| 147 | + |
| 148 | +## Redis Connection |
| 149 | + |
| 150 | +The plugin supports standard Redis connection options: |
| 151 | + |
| 152 | +- Single Redis instance |
| 153 | +- Redis with authentication |
| 154 | +- Different Redis databases |
| 155 | +- Custom connection timeouts (5-second timeout for initial connection) |
| 156 | + |
| 157 | +## Cache Invalidation |
| 158 | + |
| 159 | +- **TTL-based**: Entries automatically expire after the configured TTL |
| 160 | +- **Manual**: Use `ClearCache()` to remove all entries |
| 161 | +- **Selective**: Redis CLI can be used for manual key management |
| 162 | + |
| 163 | +## Best Practices |
| 164 | + |
| 165 | +1. **Set appropriate TTL**: Balance between cache efficiency and data freshness |
| 166 | +2. **Use meaningful prefixes**: Helps organize cache keys in shared Redis instances |
| 167 | +3. **Monitor cache hit rates**: Use `GetCacheInfo()` to track cache effectiveness |
| 168 | +4. **Consider cache size**: Monitor Redis memory usage in production |
| 169 | +5. **Handle Redis failures**: Ensure your application works without caching |
| 170 | + |
| 171 | +## Security Considerations |
| 172 | + |
| 173 | +- **Sensitive Data**: Be cautious about caching responses containing sensitive information |
| 174 | +- **Redis Security**: Use password authentication and network security for Redis |
| 175 | +- **Key Collisions**: The SHA256 hash makes collisions extremely unlikely |
| 176 | +- **Data Isolation**: Use different Redis databases or prefixes for different environments |
0 commit comments