---
title: "Memcached | DreamFactory Docs"
source: "https://docs.dreamfactory.com/api-generation-and-connections/api-types/cache/memcached"
canonical_url: "https://docs.dreamfactory.com/api-generation-and-connections/api-types/cache/memcached"
converted_at: "2026-04-22T14:34:31.705Z"
format: "markdown"
converted_by: "html-to-md-ai"
---
Memcached is a high-performance, distributed memory caching system designed for simplicity and speed. DreamFactory supports Memcached as a caching backend for API response caching and general-purpose key-value storage.

---

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

- **Simple key-value caching**: Store and retrieve data with minimal overhead

- **API response caching**: Cache database query results

- **Distributed caching**: Share cache across multiple application servers

- **High-throughput scenarios**: When raw speed matters more than features

---

## Memcached vs Redis[​](#memcached-vs-redis)

FeatureMemcachedRedisData typesStrings onlyStrings, lists, sets, hashesMaximum key size250 bytes512 MBMaximum value size1 MB (default)512 MBPersistenceNoneOptionalReplicationNoneMaster-slaveMemory efficiencyExcellentGoodThreadingMulti-threadedSingle-threadedComplexitySimpleFeature-rich

**Choose Memcached when:**

- You need simple key-value caching

- Maximum memory efficiency is critical

- You don't need persistence or advanced data structures

- Multi-threaded performance is beneficial

**Choose Redis when:**

- You need sessions, queues, or pub/sub

- Data persistence is required

- You use complex data structures

---

## Prerequisites[​](#prerequisites)

### Install Memcached[​](#install-memcached)

**Ubuntu/Debian:**

```
sudo apt updatesudo apt install memcached libmemcached-toolssudo systemctl enable memcachedsudo systemctl start memcached
```

**CentOS/RHEL:**

```
sudo yum install memcachedsudo systemctl enable memcachedsudo systemctl start memcached
```

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

```
echo "stats" | nc localhost 11211
```

### PHP Extension[​](#php-extension)

DreamFactory requires the PHP Memcached extension:

```
sudo apt install php-memcachedsudo systemctl restart php-fpm
```

---

## Configuring Memcached in DreamFactory[​](#configuring-memcached-in-dreamfactory)

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

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

```
CACHE_DRIVER=memcachedMEMCACHED_HOST=localhostMEMCACHED_PORT=11211
```

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

VariableRequiredDefaultDescription`CACHE_DRIVER`Yes`file`Set to `memcached` to enable`MEMCACHED_HOST`Yes`localhost`Memcached server hostname`MEMCACHED_PORT`No`11211`Memcached server port`MEMCACHED_PERSISTENT_ID`No-Persistent connection identifier`MEMCACHED_USERNAME`No-SASL authentication username`MEMCACHED_PASSWORD`No-SASL authentication password

### Multiple Servers[​](#multiple-servers)

For distributed caching across multiple Memcached servers:

```
MEMCACHED_HOST=server1.example.com:11211,server2.example.com:11211,server3.example.com:11211
```

---

## Creating a Memcached Cache Service[​](#creating-a-memcached-cache-service)

Create a Memcached 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 **Memcached**.

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

FieldDescriptionExampleNameService name (used in API URL)`memcache`LabelDisplay name`Memcached`DescriptionService description`Application cache`

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

FieldRequiredDefaultDescriptionHostNo`127.0.0.1`Memcached server hostname or IPPortNo`11211`Memcached port numberDefault 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 operations.

---

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

MethodEndpointDescription`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

noteMemcached does not support listing all keys. Use `GET` with specific keys only.

---

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

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

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

**Response:**

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

### Store JSON Data[​](#store-json-data)

Values are automatically serialized:

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

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

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

**Response:**

```
{  "key": "user:123:name",  "value": "John Doe"}
```

### Retrieve Multiple Values[​](#retrieve-multiple-values)

```
curl -X GET "https://example.com/api/v2/memcache?keys=user:123:name,user:456:name" \  -H "X-DreamFactory-API-Key: YOUR_API_KEY"
```

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

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

### Flush All Keys[​](#flush-all-keys)

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

warningFlushing deletes all cached data. Use with caution in production.

---

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

Set expiration times when storing values:

TTL ValueBehaviorPositive integer (< 30 days)Expire after N seconds`0`No expirationUnix timestamp (> 30 days)Expire at specific time

### Memcached TTL Behavior[​](#memcached-ttl-behavior)

Memcached has a maximum TTL of 30 days (2592000 seconds). Values larger than this are interpreted as Unix timestamps.

```
# Expires in 1 hour{"key": "temp:data", "value": "...", "ttl": 3600}# Expires in 7 days{"key": "weekly:report", "value": "...", "ttl": 604800}# Expires at specific Unix timestamp{"key": "event:data", "value": "...", "ttl": 1740000000}
```

---

## Memcached Configuration[​](#memcached-configuration)

### Server Configuration[​](#server-configuration)

Edit `/etc/memcached.conf`:

```
# Listen address (localhost only for security)-l 127.0.0.1# Port-p 11211# Memory limit (MB)-m 256# Maximum connections-c 1024# Run as user-u memcached
```

### Memory Allocation[​](#memory-allocation)

SettingDescription`-m 256`Allocate 256 MB for cache storage`-I 2m`Maximum item size (default 1 MB)`-f 1.25`Chunk size growth factor

### Security[​](#security)

**Bind to localhost:**

```
-l 127.0.0.1
```

**SASL Authentication** (requires libmemcached with SASL):

```
-S
```

---

## Distributed Caching[​](#distributed-caching)

### Consistent Hashing[​](#consistent-hashing)

When using multiple Memcached servers, DreamFactory uses consistent hashing to distribute keys. This minimizes cache invalidation when servers are added or removed.

### Server Weights[​](#server-weights)

Assign weights to servers based on capacity:

```
MEMCACHED_HOST=server1.example.com:11211:2,server2.example.com:11211:1
```

Server1 receives twice as many keys as server2.

### Failover Behavior[​](#failover-behavior)

If a Memcached server becomes unavailable:

- Affected keys become cache misses

- Keys are redistributed to remaining servers

- No data is automatically replicated

---

## Monitoring[​](#monitoring)

### Key Metrics[​](#key-metrics)

MetricDescriptionConcern Level`curr_items`Current cached items-`get_hits`Successful cache hitsHigher is better`get_misses`Cache missesHigh ratio indicates issues`evictions`Items evicted for memoryAny eviction may be concern`bytes_read`Network bytes read-`bytes_written`Network bytes written-

### Memcached Stats[​](#memcached-stats)

```
# Get all statsecho "stats" | nc localhost 11211# Get specific statsecho "stats items" | nc localhost 11211echo "stats slabs" | nc localhost 11211
```

### Calculate Hit Ratio[​](#calculate-hit-ratio)

```
hit_ratio = get_hits / (get_hits + get_misses)
```

A healthy cache should have a hit ratio above 80%.

---

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

Error CodeMessageCauseSolution400Bad RequestInvalid key or valueCheck key length (max 250 bytes)401UnauthorizedMissing API keyAdd API key header404Not FoundKey does not existHandle cache miss500Connection refusedServer unreachableCheck Memcached status500SERVER_ERRORValue too largeIncrease `-I` setting

### Troubleshooting[​](#troubleshooting)

```
# Check if Memcached is runningsudo systemctl status memcached# Test connectionecho "stats" | nc localhost 11211# Check memory usageecho "stats" | nc localhost 11211 | grep bytes# View logssudo journalctl -u memcached
```

---

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

### Slab Allocation[​](#slab-allocation)

Memcached allocates memory in slabs. Monitor slab usage:

```
echo "stats slabs" | nc localhost 11211
```

If certain slab classes fill up while others are empty, adjust the growth factor:

```
-f 1.1  # Smaller chunks, more classes
```

### Connection Handling[​](#connection-handling)

```
# Increase max connections-c 2048# Enable TCP_NODELAY-T
```

### UDP Mode[​](#udp-mode)

For read-heavy workloads in trusted networks:

```
-U 11211
```

warningUDP mode is vulnerable to amplification attacks. Only use in secure networks.

---

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

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

- **[Redis](/api-generation-and-connections/api-types/cache/redis)**: Feature-rich alternative

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