---
title: "Redis | DreamFactory Docs"
source: "https://docs.dreamfactory.com/api-generation-and-connections/api-types/cache/redis"
canonical_url: "https://docs.dreamfactory.com/api-generation-and-connections/api-types/cache/redis"
converted_at: "2026-04-25T06:39:33.286Z"
format: "markdown"
converted_by: "html-to-md-ai"
---
Redis is a high-performance, in-memory data store that DreamFactory uses for caching, session storage, and rate limiting. It provides sub-millisecond response times and supports advanced data structures for complex caching scenarios.

---

## Use Cases[​](#use-cases)

- **API response caching**: Store database query results for faster subsequent requests

- **Session storage**: Distribute user sessions across multiple DreamFactory instances

- **Rate limiting**: Track API request counts with automatic expiry

- **Queue backend**: Process background jobs asynchronously

- **Pub/Sub messaging**: Real-time event distribution (advanced)

---

## Prerequisites[​](#prerequisites)

### Redis Server[​](#redis-server)

Install Redis on your server or use a managed service:

**Ubuntu/Debian:**

```
sudo apt updatesudo apt install redis-serversudo systemctl enable redis-serversudo systemctl start redis-server
```

**Managed Services:**

- AWS ElastiCache for Redis

- Azure Cache for Redis

- Google Cloud Memorystore

- Redis Cloud

### Verify Installation[​](#verify-installation)

```
redis-cli ping# Expected response: PONG
```

---

## Configuring Redis in DreamFactory[​](#configuring-redis-in-dreamfactory)

### System Cache Configuration[​](#system-cache-configuration)

Set Redis as the system cache backend in your DreamFactory environment file (`.env`):

```
CACHE_DRIVER=redisREDIS_HOST=localhostREDIS_PORT=6379REDIS_PASSWORD=your_secure_passwordREDIS_DATABASE=0
```

### Configuration Options[​](#configuration-options)

VariableRequiredDefaultDescription`CACHE_DRIVER`Yes`file`Set to `redis` to enable`REDIS_HOST`Yes`localhost`Redis server hostname or IP`REDIS_PORT`No`6379`Redis server port`REDIS_PASSWORD`No-Redis authentication password`REDIS_DATABASE`No`0`Redis database number (0-15)`REDIS_PREFIX`No`dreamfactory`Key prefix for namespacing

### Session Storage[​](#session-storage)

To store sessions in Redis:

```
SESSION_DRIVER=redis
```

### Queue Backend[​](#queue-backend)

To use Redis for background job queues:

```
QUEUE_DRIVER=redis
```

---

## Creating a Redis Cache Service[​](#creating-a-redis-cache-service)

In addition to system caching, you can create a Redis service for direct cache API access.

### Step 1: Navigate to API Generation[​](#step-1-navigate-to-api-generation)

Log in to your DreamFactory instance and select **API Generation & Connections**. Set API Type to **Cache**.

### Step 2: Create New Service[​](#step-2-create-new-service)

Click the plus button and select **Redis**.

### Step 3: Configure Service Details[​](#step-3-configure-service-details)

FieldDescriptionExampleNameService name (used in API URL)`redis`LabelDisplay name`Redis Cache`DescriptionService description`Application cache service`

### Step 4: Configure Connection[​](#step-4-configure-connection)

FieldRequiredDefaultDescriptionHostNo`127.0.0.1`Redis server hostname or IPPortNo`6379`Redis port numberPasswordNo-Authentication passwordDatabase IndexNo`0`Redis database number (0-15)Default TTLNo`300`Time to live in minutes before cached values expire

### Step 5: Save and Test[​](#step-5-save-and-test)

Save the service and use API Docs to test cache operations.

---

## API Endpoints[​](#api-endpoints)

MethodEndpointDescription`GET``/api/v2/{service}/`List all keys (use sparingly)`GET``/api/v2/{service}/{key}`Get value by key`POST``/api/v2/{service}`Store one or more key-value pairs`PUT``/api/v2/{service}/{key}`Update existing key`DELETE``/api/v2/{service}/{key}`Delete a key`DELETE``/api/v2/{service}`Flush all keys (dangerous)

---

## API Examples[​](#api-examples)

### Store a Value[​](#store-a-value)

```
curl -X POST "https://example.com/api/v2/redis" \  -H "X-DreamFactory-API-Key: YOUR_API_KEY" \  -H "Content-Type: application/json" \  -d '{    "resource": [      {        "key": "user:123:profile",        "value": {"name": "John Doe", "email": "[email protected]"},        "ttl": 3600      }    ]  }'
```

**Response:**

```
{  "resource": [    {      "key": "user:123:profile",      "success": true    }  ]}
```

### Store Multiple Values[​](#store-multiple-values)

```
curl -X POST "https://example.com/api/v2/redis" \  -H "X-DreamFactory-API-Key: YOUR_API_KEY" \  -H "Content-Type: application/json" \  -d '{    "resource": [      {"key": "setting:theme", "value": "dark", "ttl": 86400},      {"key": "setting:language", "value": "en", "ttl": 86400},      {"key": "setting:timezone", "value": "UTC", "ttl": 86400}    ]  }'
```

### Retrieve a Value[​](#retrieve-a-value)

```
curl -X GET "https://example.com/api/v2/redis/user:123:profile" \  -H "X-DreamFactory-API-Key: YOUR_API_KEY"
```

**Response:**

```
{  "key": "user:123:profile",  "value": {    "name": "John Doe",    "email": "[email protected]"  }}
```

### Delete a Key[​](#delete-a-key)

```
curl -X DELETE "https://example.com/api/v2/redis/user:123:profile" \  -H "X-DreamFactory-API-Key: YOUR_API_KEY"
```

### Check if Key Exists[​](#check-if-key-exists)

```
curl -X GET "https://example.com/api/v2/redis/user:123:profile?check_exist=true" \  -H "X-DreamFactory-API-Key: YOUR_API_KEY"
```

**Response:**

```
{  "key": "user:123:profile",  "exists": true}
```

---

## TTL (Time-To-Live)[​](#ttl-time-to-live)

Set expiration times when storing values:

TTL ValueBehaviorPositive integerExpire after N seconds`0`No expiration (persist indefinitely)`-1`Use default TTL from service config

### Recommended TTL Values[​](#recommended-ttl-values)

Data TypeTTL (seconds)DurationSession data180030 minutesUser profiles3005 minutesReference data8640024 hoursRate limit counters601 minuteReal-time data3030 seconds

---

## Redis Configuration Best Practices[​](#redis-configuration-best-practices)

### Security[​](#security)

**Bind to localhost or private network:**

```
# /etc/redis/redis.confbind 127.0.0.1
```

**Require authentication:**

```
requirepass your_strong_password_here
```

**Disable dangerous commands:**

```
rename-command FLUSHDB ""rename-command FLUSHALL ""rename-command DEBUG ""
```

### Memory Management[​](#memory-management)

**Set memory limit:**

```
maxmemory 256mb
```

**Configure eviction policy:**

```
maxmemory-policy allkeys-lru
```

PolicyDescription`noeviction`Return error when memory limit reached`allkeys-lru`Evict least recently used keys (recommended)`volatile-lru`Evict LRU keys with TTL set`allkeys-random`Random eviction

### Persistence[​](#persistence)

**RDB snapshots (default):**

```
save 900 1    # Save if 1 key changed in 900 secondssave 300 10   # Save if 10 keys changed in 300 secondssave 60 10000 # Save if 10000 keys changed in 60 seconds
```

**AOF for durability:**

```
appendonly yesappendfsync everysec
```

---

## High Availability[​](#high-availability)

### Redis Sentinel[​](#redis-sentinel)

For automatic failover:

```
REDIS_SENTINEL_HOST=sentinel1.example.com,sentinel2.example.comREDIS_SENTINEL_PORT=26379REDIS_SENTINEL_MASTER=mymaster
```

### Redis Cluster[​](#redis-cluster)

For horizontal scaling, configure multiple Redis nodes with clustering enabled.

---

## Monitoring[​](#monitoring)

### Key Metrics to Watch[​](#key-metrics-to-watch)

MetricDescriptionAlert Threshold`used_memory`Current memory usage> 80% of maxmemory`connected_clients`Active connections> 80% of maxclients`keyspace_hits`Cache hit count-`keyspace_misses`Cache miss countHigh miss ratio`evicted_keys`Keys removed due to memoryAny eviction

### Redis CLI Commands[​](#redis-cli-commands)

```
# Check server statusredis-cli info# Monitor memoryredis-cli info memory# Check connected clientsredis-cli client list# Get hit/miss ratioredis-cli info stats | grep keyspace
```

---

## Common Errors[​](#common-errors)

Error CodeMessageCauseSolution400Bad RequestInvalid key or valueCheck request format401UnauthorizedMissing API keyAdd API key header404Not FoundKey does not existHandle cache miss500Connection refusedRedis server unreachableCheck Redis server status500NOAUTHAuthentication requiredAdd REDIS_PASSWORD to .env

### Troubleshooting Connection Issues[​](#troubleshooting-connection-issues)

```
# Test Redis connectivityredis-cli -h localhost -p 6379 ping# Test with passwordredis-cli -h localhost -p 6379 -a your_password ping# Check Redis logssudo tail -f /var/log/redis/redis-server.log
```

---

## Performance Tuning[​](#performance-tuning)

### Connection Pooling[​](#connection-pooling)

Configure persistent connections in Laravel/DreamFactory:

```
REDIS_CLIENT=phpredis
```

### Pipelining[​](#pipelining)

For bulk operations, the API supports batch requests that are automatically pipelined.

### Key Design[​](#key-design)

- Use colons `:` as separators: `user:123:profile`

- Keep keys short but descriptive

- Use consistent naming conventions

- Avoid spaces and special characters

---

## Next Steps[​](#next-steps)

- **[Cache Overview](/api-generation-and-connections/api-types/cache/cache-overview)**: Compare caching backends

- **[Memcached](/api-generation-and-connections/api-types/cache/memcached)**: Alternative caching option

- **[Performance Tuning](/administration/performance-tuning)**: Optimize DreamFactory