---
title: "View source for Memcached - DreamFactory Wiki"
source: "http://wiki.dreamfactory.com/index.php?action=edit&title=Memcached"
canonical_url: "http://wiki.dreamfactory.com/index.php?action=edit&title=Memcached"
converted_at: "2026-04-17T00:37:50.151Z"
format: "markdown"
converted_by: "html-to-md-ai"
---
[]()
	
	
	
	# View source for Memcached

	
		
		← [Memcached](/Memcached)
		
		
		
		[Jump to navigation](#mw-head)
		[Jump to search](#searchInput)
		You do not have permission to edit this page, for the following reason:

The action you have requested is limited to users in the group: [Users](/index.php?title=DreamFactory_Wiki:Users&action=edit&redlink=1).

---

You can view and copy the source of this page.

{{#seo:
|title=Memcached - DreamFactory Documentation
|title_mode=replace
|canonical=https://wiki.dreamfactory.com/Memcached
|og:title=Memcached
|og:type=article
|og:site_name=DreamFactory Documentation
}}
= Memcached =

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 ==

* '''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 ==

{| class="wikitable"
! Feature !! Memcached !! Redis
|-
| Data types || Strings only || Strings, lists, sets, hashes
|-
| Maximum key size || 250 bytes || 512 MB
|-
| Maximum value size || 1 MB (default) || 512 MB
|-
| Persistence || None || Optional
|-
| Replication || None || Master-slave
|-
| Memory efficiency || Excellent || Good
|-
| Threading || Multi-threaded || Single-threaded
|-
| Complexity || Simple || Feature-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 ==

=== Install Memcached ===

'''Ubuntu/Debian:'''
&lt;syntaxhighlight lang="bash">
sudo apt update
sudo apt install memcached libmemcached-tools
sudo systemctl enable memcached
sudo systemctl start memcached
&lt;/syntaxhighlight>

'''CentOS/RHEL:'''
&lt;syntaxhighlight lang="bash">
sudo yum install memcached
sudo systemctl enable memcached
sudo systemctl start memcached
&lt;/syntaxhighlight>

=== Verify Installation ===

&lt;syntaxhighlight lang="bash">
echo "stats" | nc localhost 11211
&lt;/syntaxhighlight>

=== PHP Extension ===

DreamFactory requires the PHP Memcached extension:

&lt;syntaxhighlight lang="bash">
sudo apt install php-memcached
sudo systemctl restart php-fpm
&lt;/syntaxhighlight>

----

== Configuring Memcached in DreamFactory ==

=== System Cache Configuration ===

Set Memcached as the system cache backend in your DreamFactory environment file (&lt;code>.env&lt;/code>):

&lt;syntaxhighlight lang="text">
CACHE_DRIVER=memcached
MEMCACHED_HOST=localhost
MEMCACHED_PORT=11211
&lt;/syntaxhighlight>

=== Configuration Options ===

{| class="wikitable"
! Variable !! Required !! Default !! Description
|-
| &lt;code>CACHE_DRIVER&lt;/code> || Yes || &lt;code>file&lt;/code> || Set to &lt;code>memcached&lt;/code> to enable
|-
| &lt;code>MEMCACHED_HOST&lt;/code> || Yes || &lt;code>localhost&lt;/code> || Memcached server hostname
|-
| &lt;code>MEMCACHED_PORT&lt;/code> || No || &lt;code>11211&lt;/code> || Memcached server port
|-
| &lt;code>MEMCACHED_PERSISTENT_ID&lt;/code> || No || - || Persistent connection identifier
|-
| &lt;code>MEMCACHED_USERNAME&lt;/code> || No || - || SASL authentication username
|-
| &lt;code>MEMCACHED_PASSWORD&lt;/code> || No || - || SASL authentication password
|}

=== Multiple Servers ===

For distributed caching across multiple Memcached servers:

&lt;syntaxhighlight lang="text">
MEMCACHED_HOST=server1.example.com:11211,server2.example.com:11211,server3.example.com:11211
&lt;/syntaxhighlight>

----

== Creating a Memcached Cache Service ==

Create a Memcached service for direct cache API access.

=== Step 1: Navigate to API Generation ===

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

=== Step 2: Create New Service ===

Click the plus button and select '''Memcached'''.

=== Step 3: Configure Service Details ===

{| class="wikitable"
! Field !! Description !! Example
|-
| Name || Service name (used in API URL) || &lt;code>memcache&lt;/code>
|-
| Label || Display name || &lt;code>Memcached&lt;/code>
|-
| Description || Service description || &lt;code>Application cache&lt;/code>
|}

=== Step 4: Configure Connection ===

{| class="wikitable"
! Field !! Required !! Default !! Description
|-
| Host || No || &lt;code>127.0.0.1&lt;/code> || Memcached server hostname or IP
|-
| Port || No || &lt;code>11211&lt;/code> || Memcached port number
|-
| Default TTL || No || &lt;code>300&lt;/code> || Time to live in minutes before cached values expire
|}

=== Step 5: Save and Test ===

Save the service and use API Docs to test operations.

----

== API Endpoints ==

{| class="wikitable"
! Method !! Endpoint !! Description
|-
| &lt;code>GET&lt;/code> || &lt;code>/api/v2/{service}/{key}&lt;/code> || Get value by key
|-
| &lt;code>POST&lt;/code> || &lt;code>/api/v2/{service}&lt;/code> || Store one or more key-value pairs
|-
| &lt;code>PUT&lt;/code> || &lt;code>/api/v2/{service}/{key}&lt;/code> || Update existing key
|-
| &lt;code>DELETE&lt;/code> || &lt;code>/api/v2/{service}/{key}&lt;/code> || Delete a key
|-
| &lt;code>DELETE&lt;/code> || &lt;code>/api/v2/{service}&lt;/code> || Flush all keys
|}

{{Note|Memcached does not support listing all keys. Use &lt;code>GET&lt;/code> with specific keys only.}}

----

== API Examples ==

=== Store a Value ===

&lt;syntaxhighlight lang="bash">
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
      }
    ]
  }'
&lt;/syntaxhighlight>

'''Response:'''
&lt;syntaxhighlight lang="json">
{
  "resource": [
    {
      "key": "user:123:name",
      "success": true
    }
  ]
}
&lt;/syntaxhighlight>

=== Store JSON Data ===

Values are automatically serialized:

&lt;syntaxhighlight lang="bash">
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
      }
    ]
  }'
&lt;/syntaxhighlight>

=== Retrieve a Value ===

&lt;syntaxhighlight lang="bash">
curl -X GET "https://example.com/api/v2/memcache/user:123:name" \
  -H "X-DreamFactory-API-Key: YOUR_API_KEY"
&lt;/syntaxhighlight>

'''Response:'''
&lt;syntaxhighlight lang="json">
{
  "key": "user:123:name",
  "value": "John Doe"
}
&lt;/syntaxhighlight>

=== Retrieve Multiple Values ===

&lt;syntaxhighlight lang="bash">
curl -X GET "https://example.com/api/v2/memcache?keys=user:123:name,user:456:name" \
  -H "X-DreamFactory-API-Key: YOUR_API_KEY"
&lt;/syntaxhighlight>

=== Delete a Key ===

&lt;syntaxhighlight lang="bash">
curl -X DELETE "https://example.com/api/v2/memcache/user:123:name" \
  -H "X-DreamFactory-API-Key: YOUR_API_KEY"
&lt;/syntaxhighlight>

=== Flush All Keys ===

&lt;syntaxhighlight lang="bash">
curl -X DELETE "https://example.com/api/v2/memcache" \
  -H "X-DreamFactory-API-Key: YOUR_API_KEY"
&lt;/syntaxhighlight>

{{Warning|Flushing deletes all cached data. Use with caution in production.}}

----

== TTL (Time-To-Live) ==

Set expiration times when storing values:

{| class="wikitable"
! TTL Value !! Behavior
|-
| Positive integer (&lt; 30 days) || Expire after N seconds
|-
| &lt;code>0&lt;/code> || No expiration
|-
| Unix timestamp (> 30 days) || Expire at specific time
|}

=== Memcached TTL Behavior ===

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

&lt;syntaxhighlight lang="json">
// 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}
&lt;/syntaxhighlight>

----

== Memcached Configuration ==

=== Server Configuration ===

Edit &lt;code>/etc/memcached.conf&lt;/code>:

&lt;syntaxhighlight lang="text">
# 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
&lt;/syntaxhighlight>

=== Memory Allocation ===

{| class="wikitable"
! Setting !! Description
|-
| &lt;code>-m 256&lt;/code> || Allocate 256 MB for cache storage
|-
| &lt;code>-I 2m&lt;/code> || Maximum item size (default 1 MB)
|-
| &lt;code>-f 1.25&lt;/code> || Chunk size growth factor
|}

=== Security ===

'''Bind to localhost:'''
&lt;syntaxhighlight lang="text">
-l 127.0.0.1
&lt;/syntaxhighlight>

'''SASL Authentication''' (requires libmemcached with SASL):
&lt;syntaxhighlight lang="text">
-S
&lt;/syntaxhighlight>

----

== Distributed Caching ==

=== 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 ===

Assign weights to servers based on capacity:

&lt;syntaxhighlight lang="text">
MEMCACHED_HOST=server1.example.com:11211:2,server2.example.com:11211:1
&lt;/syntaxhighlight>

Server1 receives twice as many keys as server2.

=== 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 ==

=== Key Metrics ===

{| class="wikitable"
! Metric !! Description !! Concern Level
|-
| &lt;code>curr_items&lt;/code> || Current cached items || -
|-
| &lt;code>get_hits&lt;/code> || Successful cache hits || Higher is better
|-
| &lt;code>get_misses&lt;/code> || Cache misses || High ratio indicates issues
|-
| &lt;code>evictions&lt;/code> || Items evicted for memory || Any eviction may be concern
|-
| &lt;code>bytes_read&lt;/code> || Network bytes read || -
|-
| &lt;code>bytes_written&lt;/code> || Network bytes written || -
|}

=== Memcached Stats ===

&lt;syntaxhighlight lang="bash">
# Get all stats
echo "stats" | nc localhost 11211

# Get specific stats
echo "stats items" | nc localhost 11211
echo "stats slabs" | nc localhost 11211
&lt;/syntaxhighlight>

=== Calculate Hit Ratio ===

&lt;syntaxhighlight lang="text">
hit_ratio = get_hits / (get_hits + get_misses)
&lt;/syntaxhighlight>

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

----

== Common Errors ==

{| class="wikitable"
! Error Code !! Message !! Cause !! Solution
|-
| 400 || Bad Request || Invalid key or value || Check key length (max 250 bytes)
|-
| 401 || Unauthorized || Missing API key || Add API key header
|-
| 404 || Not Found || Key does not exist || Handle cache miss
|-
| 500 || Connection refused || Server unreachable || Check Memcached status
|-
| 500 || SERVER_ERROR || Value too large || Increase &lt;code>-I&lt;/code> setting
|}

=== Troubleshooting ===

&lt;syntaxhighlight lang="bash">
# Check if Memcached is running
sudo systemctl status memcached

# Test connection
echo "stats" | nc localhost 11211

# Check memory usage
echo "stats" | nc localhost 11211 | grep bytes

# View logs
sudo journalctl -u memcached
&lt;/syntaxhighlight>

----

== Performance Tuning ==

=== Slab Allocation ===

Memcached allocates memory in slabs. Monitor slab usage:

&lt;syntaxhighlight lang="bash">
echo "stats slabs" | nc localhost 11211
&lt;/syntaxhighlight>

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

&lt;syntaxhighlight lang="text">
-f 1.1  # Smaller chunks, more classes
&lt;/syntaxhighlight>

=== Connection Handling ===

&lt;syntaxhighlight lang="text">
# Increase max connections
-c 2048

# Enable TCP_NODELAY
-T
&lt;/syntaxhighlight>

=== UDP Mode ===

For read-heavy workloads in trusted networks:

&lt;syntaxhighlight lang="text">
-U 11211
&lt;/syntaxhighlight>

{{Warning|UDP mode is vulnerable to amplification attacks. Only use in secure networks.}}

----

== Next Steps ==

* '''[[Cache Overview]]''': Compare caching backends
* '''[[Redis]]''': Feature-rich alternative
* '''[[Getting_Started/Optimizing_Dreamfactory/Database|Performance Tuning]]''': Optimize DreamFactory

[[Category:API]]
Templates used on this page:

- [Template:Note](/Template:Note) ([view source](/index.php?title=Template:Note&action=edit))
- [Template:Warning](/Template:Warning) ([view source](/index.php?title=Template:Warning&action=edit))

Return to [Memcached](/Memcached).

Retrieved from "[https://wiki.dreamfactory.com/Memcached](https://wiki.dreamfactory.com/Memcached)"