Skip to content

CRD Reference ​

Complete field reference for the Memcached Custom Resource Definition.


Resource Info ​

PropertyValue
API Groupmemcached.c5c3.io
API Versionv1beta1 (storage version), v1alpha1 (deprecated)
KindMemcached
List KindMemcachedList
ScopeNamespaced
Subresourcesstatus

MemcachedSpec ​

MemcachedSpec defines the desired state of a Memcached instance.

FieldTypeDefaultValidationDescription
replicas*int321min=0, max=64Number of Memcached pods
image*string"memcached:1.6"--Container image for the Memcached server
resources*ResourceRequirements----CPU/memory requests and limits for the Memcached container
memcached*MemcachedConfig----Memcached server configuration parameters
highAvailability*HighAvailabilitySpec----High-availability settings (anti-affinity, PDB, topology spread, graceful shutdown)
monitoring*MonitoringSpec----Monitoring and metrics configuration
security*SecuritySpec----Security settings (security contexts, SASL, TLS, NetworkPolicy)
autoscaling*AutoscalingSpec----Horizontal pod autoscaling configuration
service*ServiceSpec----Configuration for the headless Service

MemcachedConfig ​

MemcachedConfig defines the Memcached server runtime configuration. Each field maps to a memcached command-line flag.

FieldTypeDefaultValidationMemcached FlagDescription
maxMemoryMBint3264min=16, max=65536-mMaximum memory for item storage in megabytes
maxConnectionsint321024min=1, max=65536-cMaximum number of simultaneous connections
threadsint324min=1, max=128-tNumber of worker threads
maxItemSizestring"1m"pattern=^[0-9]+(k|m)$-IMaximum size of an item (e.g., "1m", "2m", "512k")
verbosityint320min=0, max=2-v / -vvLogging verbosity level (0=none, 1=verbose, 2=very verbose)
extraArgs[]string[]--(raw)Additional command-line arguments passed directly to the Memcached process

Verbosity Mapping ​

ValueMemcached FlagEffect
0(none)No verbose logging
1-vVerbose logging
2-vvVery verbose logging

HighAvailabilitySpec ​

HighAvailabilitySpec defines high-availability settings for Memcached pods.

FieldTypeDefaultValidationDescription
antiAffinityPreset*AntiAffinityPreset"soft"enum: soft, hardControls pod anti-affinity scheduling preset
topologySpreadConstraints[]TopologySpreadConstraint----Defines how pods are spread across topology domains
podDisruptionBudget*PDBSpec----PodDisruptionBudget configuration
gracefulShutdown*GracefulShutdownSpec----Configures preStop lifecycle hooks and termination grace period

AntiAffinityPreset Values ​

ValueScheduling RuleBehavior
softpreferredDuringSchedulingIgnoredDuringExecutionBest-effort spreading; pods prefer different nodes but can be co-located if necessary
hardrequiredDuringSchedulingIgnoredDuringExecutionStrict spreading; pods must be on different nodes

GracefulShutdownSpec ​

GracefulShutdownSpec defines the graceful shutdown configuration, allowing in-flight connections to drain before pod termination.

FieldTypeDefaultValidationDescription
enabledboolfalse--Controls whether graceful shutdown is configured
preStopDelaySecondsint3210min=1, max=300Number of seconds the preStop hook sleeps to allow connection draining
terminationGracePeriodSecondsint6430min=1, max=600Duration in seconds the pod needs to terminate gracefully. Must exceed preStopDelaySeconds to allow the hook to complete before SIGKILL.

PDBSpec ​

PDBSpec defines the PodDisruptionBudget configuration. When enabled, a PDB is created to guarantee a minimum number of pods remain available during voluntary disruptions (node drains, upgrades).

FieldTypeDefaultValidationDescription
enabledboolfalse--Controls whether a PodDisruptionBudget is created
minAvailable*IntOrString----Minimum number of pods that must be available during disruption. Can be an absolute number (e.g., 1) or a percentage (e.g., "50%"). The controller defaults to 1 when neither minAvailable nor maxUnavailable is set.
maxUnavailable*IntOrString----Maximum number of pods that can be unavailable during disruption. Can be an absolute number or a percentage.

Note: Only one of minAvailable or maxUnavailable should be set. If both are specified, the behavior follows the standard Kubernetes PDB semantics.


MonitoringSpec ​

MonitoringSpec defines monitoring and metrics configuration. When enabled, a Prometheus memcached-exporter sidecar is injected into the Memcached pods.

FieldTypeDefaultValidationDescription
enabledboolfalse--Controls whether monitoring is active (enables the exporter sidecar)
exporterImage*string"prom/memcached-exporter:v0.15.4"--Container image for the memcached-exporter sidecar
exporterResources*ResourceRequirements----Resource requests/limits for the exporter sidecar container
serviceMonitor*ServiceMonitorSpec----Prometheus ServiceMonitor resource configuration

ServiceMonitorSpec ​

ServiceMonitorSpec defines the Prometheus ServiceMonitor configuration. The ServiceMonitor is only created when the ServiceMonitor CRD exists in the cluster (i.e., the Prometheus Operator is installed).

FieldTypeDefaultValidationDescription
additionalLabelsmap[string]string----Extra labels added to the ServiceMonitor resource (e.g., release: prometheus)
intervalstring"30s"--Prometheus scrape interval
scrapeTimeoutstring"10s"--Prometheus scrape timeout

SecuritySpec ​

SecuritySpec defines security settings for Memcached, including pod/container security contexts, authentication, encryption, and network policy.

FieldTypeDefaultValidationDescription
podSecurityContext*PodSecurityContext----Security context applied at the pod level
containerSecurityContext*SecurityContext----Security context applied to the Memcached container
sasl*SASLSpec----Optional SASL authentication configuration
tls*TLSSpec----Optional TLS encryption configuration
networkPolicy*NetworkPolicySpec----Kubernetes NetworkPolicy configuration for Memcached pods

SASLSpec ​

SASLSpec defines SASL authentication configuration. When enabled, the operator mounts the credentials Secret into the container and adds the -S flag to Memcached.

FieldTypeDefaultValidationDescription
enabledboolfalse--Controls whether SASL authentication is active
credentialsSecretRefLocalObjectReference----Reference to the Secret containing SASL credentials. The Secret must contain a password-file key with the SASL password file content.

TLSSpec ​

TLSSpec defines TLS encryption configuration. When enabled, the operator mounts the certificate Secret and configures memcached with TLS flags (--enable-ssl, --ssl-cert, --ssl-key, --ssl-ca-cert).

FieldTypeDefaultValidationDescription
enabledboolfalse--Controls whether TLS encryption is active
certificateSecretRefLocalObjectReference----Reference to the Secret containing TLS certificates. The Secret must contain tls.crt, tls.key, and optionally ca.crt keys.
enableClientCertboolfalse--Controls whether mutual TLS (mTLS) is required. When true, Memcached requires clients to present a valid TLS certificate. The CA certificate (ca.crt) in the Secret is used to verify client certificates.

NetworkPolicySpec ​

NetworkPolicySpec defines the Kubernetes NetworkPolicy configuration for Memcached. When enabled, a NetworkPolicy is created that restricts ingress traffic to the Memcached port (11211).

Note: In the CRD, NetworkPolicySpec is nested under spec.security.networkPolicy, not at the top level.

FieldTypeDefaultValidationDescription
enabledboolfalse--Controls whether a NetworkPolicy is created
allowedSources[]NetworkPolicyPeer----List of peers allowed to access Memcached. When empty or nil, all sources are allowed. Supports podSelector, namespaceSelector, and ipBlock.

AutoscalingSpec ​

AutoscalingSpec defines horizontal pod autoscaling configuration. When enabled is true, the operator creates an HPA targeting the Memcached StatefulSet and spec.replicas must not be set (they are mutually exclusive).

FieldTypeDefaultValidationDescription
enabledboolfalse--Controls whether horizontal pod autoscaling is active
minReplicas*int32--min=1Lower limit for the number of replicas. When nil, the HPA default (1) is used
maxReplicasint32--min=1Upper limit for the number of replicas
metrics[]MetricSpec----Specifications for calculating desired replica count. Defaulted to 80% CPU utilization when empty and autoscaling is enabled
behavior*HorizontalPodAutoscalerBehavior----Scaling behavior for Up and Down directions. Defaulted to a 300s scaleDown stabilization window when nil and autoscaling is enabled

Note: When autoscaling.enabled is true, spec.replicas must not be set. The validation webhook rejects CRs where both are specified.


ServiceSpec ​

ServiceSpec defines configuration for the headless Service created for each Memcached instance.

FieldTypeDefaultValidationDescription
annotationsmap[string]string----Custom annotations added to the Service metadata

MemcachedStatus ​

MemcachedStatus defines the observed state of a Memcached instance. The status is updated by the controller during each reconciliation cycle.

FieldTypeDescription
conditions[]metav1.ConditionStandard Kubernetes conditions representing the latest available observations of the Memcached instance's state. Uses merge-patch with type as the merge key. See Status Conditions below.
readyReplicasint32Number of Memcached pods that are ready
observedGenerationint64Most recent generation observed by the controller. Clients can compare this to metadata.generation to determine if the status is up-to-date with the latest spec changes.
serverList[]stringOne host:port entry per pod, <statefulset>-<i>.<name>.<namespace>.svc:11211, ordered by pod index. Follows the StatefulSet replica count, not pod readiness; nil when the instance has zero replicas. See serverList below.

Status Conditions ​

Condition TypeStatus ValuesDescription
AvailableTrue / FalseTrue when the StatefulSet has at least one ready pod
ProgressingTrue / FalseTrue when a rollout or scale operation is in progress
DegradedTrue / FalseTrue when fewer replicas than desired are ready
ReadyTrue / FalseTrue when all desired replicas are ready and desiredReplicas > 0. See Ready Condition below

Ready Condition ​

The Ready condition indicates whether the Memcached instance is fully operational. It is computed independently of the Available, Progressing, and Degraded conditions.

StatusReasonWhen
TrueMemcachedReadyreadyReplicas == desiredReplicas and desiredReplicas > 0
FalseMemcachedNotReadyreadyReplicas < desiredReplicas, or desiredReplicas == 0, or StatefulSet not created

The condition message provides a human-readable description of the current state (e.g., "All 3 replicas are ready", "2/3 replicas are ready", "Instance has zero desired replicas").

serverList ​

The serverList field holds one address per Memcached pod, so a client library can hash keys over the pods directly. The controller computes it on every reconciliation cycle from the StatefulSet that runs the pods. Each entry has the format:

text
<statefulset>-<i>.<name>.<namespace>.svc:11211
PartMeaning
<statefulset>Name of the StatefulSet that runs the pods (see the naming rule below)
<i>Pod index, from 0 to replicas - 1
<name>Name of the Memcached resource, which is also the name of its headless Service
<namespace>Namespace of the Memcached resource
11211Memcached port. The entry uses 11211 also when TLS is enabled

The headless Service governs the StatefulSet, so every pod gets a DNS name that stays the same when the pod restarts. A pod's name resolves once the pod is ready.

The list follows these rules:

  • The entries are ordered by pod index, starting at 0.
  • The number of entries equals the replica count of the StatefulSet (its spec.replicas, or 1 when that is unset). When autoscaling is enabled, the list grows and shrinks with the replica count the HPA sets.
  • Pod readiness does not change the list. A pod that is starting or restarting keeps its entry, and the Ready condition can be False while the list is complete.
  • The list is empty (nil) when the instance has zero replicas or when the StatefulSet does not exist yet.

The StatefulSet name equals the Memcached name when the name has at most 52 characters. A longer name is shortened to its first 43 characters, followed by - and the first 8 hex characters of the SHA-256 of the full name, which gives 52 characters in total. The <name> part of each entry is always the full Memcached name.

The limit exists because Kubernetes labels every StatefulSet pod with controller-revision-hash: <statefulset>-<hash>, where the hash has up to 10 characters, and label values are limited to 63 characters. A longer StatefulSet name could not create pods.

For a Memcached named prod-cache in the namespace production with 3 replicas, the status contains:

yaml
status:
  serverList:
    - prod-cache-0.prod-cache.production.svc:11211
    - prod-cache-1.prod-cache.production.svc:11211
    - prod-cache-2.prod-cache.production.svc:11211

Printer Columns ​

When using kubectl get memcached, the following columns are displayed:

ColumnSourceTypeDescription
Replicas.spec.replicasintegerNumber of desired Memcached pods
Ready.status.readyReplicasintegerNumber of ready Memcached pods
Age.metadata.creationTimestampdateTime since the resource was created

Webhook Behavior ​

The operator registers a defaulting webhook (mutating) and a validation webhook (validating) for Memcached resources. Both webhooks run on create and update operations.

Defaulting Rules ​

The defaulting webhook sets values for omitted fields before the resource is persisted. Fields with CRD-level defaults (via +kubebuilder:default) are handled by the API server; the webhook handles pointer fields and conditional defaults.

FieldDefaultCondition
spec.replicas1When nil
spec.image"memcached:1.6"When nil
spec.memcached.maxMemoryMB64When 0 (section initialized if nil)
spec.memcached.maxConnections1024When 0
spec.memcached.threads4When 0
spec.memcached.maxItemSize"1m"When empty
spec.monitoring.exporterImage"prom/memcached-exporter:v0.15.4"When nil (only if monitoring section exists)
spec.monitoring.serviceMonitor.interval"30s"When empty (only if serviceMonitor section exists)
spec.monitoring.serviceMonitor.scrapeTimeout"10s"When empty (only if serviceMonitor section exists)
spec.highAvailability.antiAffinityPreset"soft"When nil (only if highAvailability section exists)
spec.autoscaling.metricsCPU utilization at 80%When empty (only if autoscaling is enabled)
spec.autoscaling.behaviorscaleDown stabilization 300sWhen nil (only if autoscaling is enabled)

Validation Rules ​

The validation webhook enforces cross-field constraints that cannot be expressed with kubebuilder markers alone.

RuleConditionError
Memory limit sufficientresources.limits.memory is set and memcached section existsresources.limits.memory must be at least maxMemoryMB + 32Mi (operational overhead for connections, threads, internal structures)
PDB mutual exclusivityPDB is enabledminAvailable and maxUnavailable cannot both be set
PDB requires a budget fieldPDB is enabledOne of minAvailable or maxUnavailable must be set
PDB minAvailable < replicasPDB is enabled with integer minAvailableminAvailable must be strictly less than replicas
Graceful shutdown timingGraceful shutdown is enabledterminationGracePeriodSeconds must exceed preStopDelaySeconds
SASL secret requiredsecurity.sasl.enabled is truecredentialsSecretRef.name must be non-empty
TLS secret requiredsecurity.tls.enabled is truecertificateSecretRef.name must be non-empty
Replicas/autoscaling mutexautoscaling.enabled is truespec.replicas must not be set
minReplicas <= maxReplicasautoscaling.enabled is true with minReplicas setminReplicas must not exceed maxReplicas
CPU request for HPAautoscaling.enabled with CPU utilization metricresources.requests.cpu must be set

Examples ​

Minimal ​

The simplest valid Memcached resource. All fields use their defaults (1 replica, memcached:1.6 image, 64MB memory, 1024 max connections, 4 threads).

yaml
apiVersion: memcached.c5c3.io/v1beta1
kind: Memcached
metadata:
  name: basic-cache
  namespace: default
spec: {}

Full ​

A comprehensive example using all available fields.

yaml
apiVersion: memcached.c5c3.io/v1beta1
kind: Memcached
metadata:
  name: prod-cache
  namespace: production
spec:
  replicas: 3
  image: memcached:1.6
  resources:
    requests:
      cpu: 250m
      memory: 256Mi
    limits:
      cpu: "1"
      memory: 512Mi

  memcached:
    maxMemoryMB: 256
    maxConnections: 2048
    threads: 4
    maxItemSize: "2m"
    verbosity: 0
    extraArgs: []

  highAvailability:
    antiAffinityPreset: soft
    topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: ScheduleAnyway
    podDisruptionBudget:
      enabled: true
      minAvailable: 1
    gracefulShutdown:
      enabled: true
      preStopDelaySeconds: 10
      terminationGracePeriodSeconds: 30

  monitoring:
    enabled: true
    exporterImage: prom/memcached-exporter:v0.15.4
    exporterResources:
      requests:
        cpu: 50m
        memory: 32Mi
      limits:
        cpu: 100m
        memory: 64Mi
    serviceMonitor:
      additionalLabels:
        release: prometheus
      interval: 30s
      scrapeTimeout: 10s

  security:
    podSecurityContext:
      runAsNonRoot: true
      runAsUser: 11211
      runAsGroup: 11211
      fsGroup: 11211
      seccompProfile:
        type: RuntimeDefault
    containerSecurityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
          - ALL
    sasl:
      enabled: true
      credentialsSecretRef:
        name: memcached-sasl-credentials
    tls:
      enabled: true
      certificateSecretRef:
        name: memcached-tls
      enableClientCert: true
    networkPolicy:
      enabled: true
      allowedSources:
        - podSelector:
            matchLabels:
              app: keystone
        - namespaceSelector:
            matchLabels:
              team: platform

  service:
    annotations:
      prometheus.io/scrape: "true"
      prometheus.io/port: "9150"

High-Availability with Monitoring ​

A production-oriented configuration focusing on availability and observability.

yaml
apiVersion: memcached.c5c3.io/v1beta1
kind: Memcached
metadata:
  name: ha-cache
  namespace: production
spec:
  replicas: 3
  resources:
    requests:
      cpu: 500m
      memory: 512Mi
    limits:
      cpu: "2"
      memory: 1Gi
  memcached:
    maxMemoryMB: 512
    maxConnections: 2048
    threads: 4
  highAvailability:
    antiAffinityPreset: soft
    topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: ScheduleAnyway
    podDisruptionBudget:
      enabled: true
      minAvailable: 2
    gracefulShutdown:
      enabled: true
      preStopDelaySeconds: 15
      terminationGracePeriodSeconds: 45
  monitoring:
    enabled: true
    serviceMonitor:
      additionalLabels:
        release: kube-prometheus-stack
      interval: 15s

Autoscaling ​

A configuration using horizontal pod autoscaling instead of static replicas.

yaml
apiVersion: memcached.c5c3.io/v1beta1
kind: Memcached
metadata:
  name: autoscaled-cache
  namespace: production
spec:
  image: memcached:1.6
  resources:
    requests:
      cpu: 500m
      memory: 256Mi
    limits:
      cpu: "2"
      memory: 512Mi
  memcached:
    maxMemoryMB: 256
    maxConnections: 2048
    threads: 4
  autoscaling:
    enabled: true
    minReplicas: 2
    maxReplicas: 10