memcached

by ScriptonBasestar

Helm chartv0.4.0App 1.6.39BSD-3-Clause

A Helm chart for Memcached - high-performance distributed memory caching system

About this chart

Memcached Helm Chart

Memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

⚠️ Production Consideration

For production environments requiring advanced management, consider using Memcached Operator:

  • ✅ Automated cluster management
  • ✅ CRD-based configuration
  • ✅ Declarative deployment model
  • ✅ Kubernetes-native management

This chart is recommended for:

  • Development/testing environments
  • Simple caching needs
  • Single or few-replica deployments
  • Minimal operational overhead

Features

  • ✅ Deployment-based for horizontal scaling
  • ✅ Simple command-line configuration
  • ✅ No database required (pure cache)
  • ✅ Liveness and readiness probes
  • ✅ Resource limits and requests
  • ✅ Security context (non-root user, read-only filesystem)
  • ✅ Horizontal Pod Autoscaling (optional)
  • ✅ Pod Disruption Budget for HA
  • ✅ Network Policy support
  • ✅ ServiceMonitor for Prometheus Operator

Prerequisites

  • Kubernetes 1.19+
  • Helm 3.2.0+

Deployment Scenarios

This chart includes three pre-configured deployment scenarios optimized for different use cases:

Home Server (values-home-single.yaml)

Minimal resources for personal servers, home labs, Raspberry Pi, or Intel NUC:

helm install memcached-home charts/memcached \
  -f charts/memcached/values-home-single.yaml

Resource allocation: 50-250m CPU, 128-256Mi RAM, 128MB cache

Startup Environment (values-startup-single.yaml)

Balanced configuration for small teams, startups, and development environments:

helm install memcached-startup charts/memcached \
  -f charts/memcached/values-startup-single.yaml

Resource allocation: 100-500m CPU, 256-512Mi RAM, 256MB cache

Production HA (values-prod-master-replica.yaml)

High availability deployment with multiple replicas and auto-scaling:

helm install memcached-prod charts/memcached \
  -f charts/memcached/values-prod-master-replica.yaml

Features: 3 replicas, pod anti-affinity, HPA (3-10 pods), PodDisruptionBudget

Resource allocation: 250m-1000m CPU, 512Mi-1Gi RAM, 512MB cache per pod

For detailed comparison and configuration examples, see the Scenario Values Guide.

Installation

1. Basic Installation

helm install my-memcached ./charts/memcached

2. Custom Configuration

Create a my-values.yaml file:

memcached:
  maxMemory: 512
  maxConnections: 2048

resources:
  limits:
    cpu: 1000m
    memory: 1Gi
  requests:
    cpu: 500m
    memory: 512Mi

Install with custom values:

helm install my-memcached ./charts/memcached -f my-values.yaml

3. Production Deployment

See values-example.yaml for production-ready configuration with:

  • Multiple replicas
  • Resource limits
  • Pod anti-affinity
  • Autoscaling enabled
  • Network policies
helm install my-memcached ./charts/memcached -f values-example.yaml

Configuration

Memcached Settings

The chart configures memcached via command-line arguments:

memcached:
  # Maximum memory to use for object storage (in megabytes)
  maxMemory: 256
  # Maximum number of simultaneous connections
  maxConnections: 1024
  # Chunk size growth factor (1.25 is default)
  chunkSizeGrowthFactor: 1.25
  # Minimum space allocated for key+value+flags
  minItemSize: 48
  # Enable or disable CAS (Check and Set) operations
  enableCas: true
  # Verbose logging (0=disabled, 1=enabled, 2=very verbose)
  verbosity: 0
  # Additional command-line arguments
  extraArgs:
    - "-o"
    - "modern"

High Availability

Enable autoscaling and pod disruption budget:

replicaCount: 3

autoscaling:
  enabled: true
  minReplicas: 3
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
  targetMemoryUtilizationPercentage: 80

podDisruptionBudget:
  enabled: true
  minAvailable: 2

affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
    - weight: 100
      podAffinityTerm:
        labelSelector:
          matchExpressions:
          - key: app.kubernetes.io/name
            operator: In
            values:
            - memcached
        topologyKey: kubernetes.io/hostname

Network Policy

Restrict network access:

networkPolicy:
  enabled: true
  ingress:
    - from:
      - podSelector:
          matchLabels:
            app: myapp
      ports:
      - protocol: TCP
        port: 11211

Monitoring

Enable Prometheus metrics collection:

serviceMonitor:
  enabled: true
  namespace: monitoring
  interval: 30s
  scrapeTimeout: 10s
  labels:
    prometheus: kube-prometheus

Common Operations

Using Makefile Commands

The chart includes a Makefile with common operations:

# Show statistics
make -f Makefile.memcached.mk mc-stats

# Check version
make -f Makefile.memcached.mk mc-version

# View settings
make -f Makefile.memcached.mk mc-settings

# View slab statistics
make -f Makefile.memcached.mk mc-slabs

# View item statistics
make -f Makefile.memcached.mk mc-items

# Port forward to memcached
make -f Makefile.memcached.mk mc-port-forward

# Flush all data (WARNING: clears all cached data)
make -f Makefile.memcached.mk mc-flush

Manual Operations

Connect to memcached manually:

# Port forward
kubectl port-forward -n default svc/my-memcached 11211:11211

# Test connection
echo "stats" | nc localhost 11211

# Set a key
echo "set mykey 0 3600 5\r\nhello" | nc localhost 11211

# Get a key
echo "get mykey" | nc localhost 11211

# Flush all data
echo "flush_all" | nc localhost 11211

Architecture

Deployment Strategy

Memcached is deployed as a Deployment (not StatefulSet) because:

  • Each memcached instance is independent
  • No data persistence required (cache only)
  • Easy horizontal scaling
  • Client-side hashing handles distribution

Security

  • Runs as non-root user (UID 11211)
  • Read-only root filesystem
  • All capabilities dropped
  • Privilege escalation disabled
  • /tmp mounted as emptyDir for temporary files

Resource Management

Default resource allocation:

resources:
  limits:
    cpu: 500m
    memory: 512Mi
  requests:
    cpu: 100m
    memory: 128Mi

Adjust based on your workload. Memory limit should be higher than maxMemory setting to account for overhead.

Troubleshooting

Check pod status

kubectl get pods -l app.kubernetes.io/name=memcached

View logs

kubectl logs -l app.kubernetes.io/name=memcached

Test connection

kubectl run -it --rm debug --image=busybox --restart=Never -- sh
# Inside the pod:
nc -zv my-memcached 11211
echo "stats" | nc my-memcached 11211

Common issues

Pod fails to start:

  • Check resource limits vs maxMemory setting
  • Verify securityContext compatibility with your cluster

High memory usage:

  • Adjust maxMemory setting
  • Check slab statistics: make -f Makefile.memcached.mk mc-slabs
  • Consider item eviction policy

Connection refused:

  • Verify service exists: kubectl get svc my-memcached
  • Check network policies
  • Verify firewall rules

Parameters

ParameterDescriptionDefault
replicaCountNumber of memcached replicas1
image.repositoryMemcached image repositorymemcached
image.tagMemcached image tag1.6.32
memcached.maxMemoryMaximum memory (MB)256
memcached.maxConnectionsMaximum connections1024
memcached.chunkSizeGrowthFactorChunk growth factor1.25
memcached.minItemSizeMinimum item size (bytes)48
memcached.enableCasEnable CAS operationstrue
memcached.verbosityLogging verbosity (0-3)0
resources.limits.cpuCPU limit500m
resources.limits.memoryMemory limit512Mi
resources.requests.cpuCPU request100m
resources.requests.memoryMemory request128Mi
autoscaling.enabledEnable HPAfalse
podDisruptionBudget.enabledEnable PDBfalse
networkPolicy.enabledEnable NetworkPolicyfalse
serviceMonitor.enabledEnable ServiceMonitorfalse

See values.yaml for full parameter list.


Backup & Recovery

Backup Strategy

Memcached is a stateless in-memory cache with no data persistence. Backup focuses on configuration and infrastructure, not cache data.

Backup Components (2 total):

ComponentPrioritySizeMethod
ConfigurationCritical<5 KBConfigMap export
Kubernetes ManifestsImportant<10 KBHelm values

Recovery Objectives:

  • RTO: < 15 minutes
  • RPO: 0 (cache is ephemeral, no data loss)

Quick Backup Commands

# 1. Backup Configuration (ConfigMap)
kubectl get configmap -n default my-memcached -o yaml > memcached-config-backup.yaml

# 2. Backup Helm Values
helm get values my-memcached -n default > memcached-values-backup.yaml

# 3. Full Infrastructure Backup
BACKUP_DIR="memcached-backup-$(date +%Y%m%d-%H%M%S)"
mkdir -p $BACKUP_DIR
kubectl get configmap -n default my-memcached -o yaml > $BACKUP_DIR/config.yaml
helm get values my-memcached -n default > $BACKUP_DIR/values.yaml
kubectl get all,pdb,networkpolicy -n default -l app.kubernetes.io/name=memcached -o yaml > $BACKUP_DIR/k8s-resources.yaml

Recovery Procedures

Configuration-Only Recovery

Restore configuration after accidental changes:

# Restore configuration
kubectl apply -f memcached-config-backup.yaml

# Restart pods to apply new configuration
kubectl rollout restart deployment/my-memcached -n default
kubectl wait --for=condition=ready pod -l app.kubernetes.io/name=memcached -n default --timeout=120s

# Verify
POD=$(kubectl get pods -n default -l app.kubernetes.io/name=memcached -o jsonpath='{.items[0].metadata.name}')
kubectl exec -n default $POD -- sh -c 'echo -e "stats settings\r\nquit\r" | nc localhost 11211'

Full Cluster Recreation

Complete recovery for cluster failure:

# Reinstall Memcached
helm install my-memcached scripton-charts/memcached \
  -f memcached-values-backup.yaml \
  -n default

# Wait for deployment
kubectl wait --for=condition=ready pod -l app.kubernetes.io/name=memcached -n default --timeout=300s

# Test functionality
POD=$(kubectl get pods -n default -l app.kubernetes.io/name=memcached -o jsonpath='{.items[0].metadata.name}')
kubectl exec -n default $POD -- sh -c 'echo -e "set test 0 60 5\r\nhello\r\nget test\r\nquit\r" | nc localhost 11211'

Best Practices

  1. Git-Based Configuration: Store values.yaml in Git repository for version control
  2. Daily Configuration Backups: Backup ConfigMap daily or before every change
  3. Off-Cluster Storage: Store backups in S3/MinIO or remote Git repository
  4. Quarterly DR Drills: Practice full cluster recovery procedures
  5. Cache Warming: Implement cache warming strategy after recovery to reduce initial cache miss rate

Detailed Guide: See docs/memcached-backup-guide.md for comprehensive backup procedures, automation examples, and disaster recovery workflows.


Security & RBAC

RBAC Configuration

The chart creates namespace-scoped RBAC resources for Memcached operations:

rbac:
  create: true  # Enable RBAC resources
  annotations: {}

Resources Created:

  • Role: Read-only access to ConfigMaps, Secrets, Pods, Services, Endpoints
  • RoleBinding: Binds ServiceAccount to Role

Permissions Granted:

  • get, list, watch on ConfigMaps (for configuration)
  • get, list, watch on Secrets (for credentials if needed)
  • get, list, watch on Pods (for health checks)
  • get, list, watch on Services/Endpoints (for service discovery)

ServiceAccount

serviceAccount:
  create: true
  name: ""  # Auto-generated if empty
  annotations: {}

Security Context

Pod-level security (runs as non-root user 11211):

podSecurityContext:
  fsGroup: 11211
  runAsUser: 11211
  runAsGroup: 11211
  runAsNonRoot: true

securityContext:
  capabilities:
    drop:
      - ALL
  readOnlyRootFilesystem: true
  runAsNonRoot: true
  runAsUser: 11211
  allowPrivilegeEscalation: false

Network Security

NetworkPolicy Example (restrict ingress to application pods only):

networkPolicy:
  enabled: true
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: my-app  # Only allow from application pods
      ports:
        - protocol: TCP
          port: 11211

Best Practices

  1. Least Privilege: Use read-only RBAC permissions
  2. Network Policies: Restrict ingress to application pods only
  3. Pod Security Standards: Enforce restricted pod security policy
  4. Non-Root User: Always run as user 11211 (never root)
  5. Read-Only Filesystem: Prevent unauthorized file modifications

Upgrading

Pre-Upgrade Checklist

Before upgrading Memcached:

  • [ ] Review Release Notes: Check Memcached releases for breaking changes
  • [ ] Backup Configuration: Export current ConfigMap and Helm values
  • [ ] Check Client Compatibility: Ensure application clients support new version
  • [ ] Test in Non-Production: Validate upgrade in dev/staging environment
  • [ ] Plan for Cache Miss: Applications must handle cache misses after upgrade

Note: Cache data is ephemeral and will be lost during upgrade (expected behavior).

Deploy memcached with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has memcached on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.

  1. Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
  2. Place the chartmemcached is pinned at v0.4.0 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
  3. ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below
opentenant validate opentenant.yaml
terraform init && terraform apply