Memcached implementation reference

This page describes how the Memcached wire is built: the text, meta and binary protocols on one port, authentication, the item store, the write-behind and sync durability modes, errors, limits and tests. For the port, proof scores, how to connect and how to re-run the differential suite, see the operator page Memcached. Authentication policy across all wires is in Security.

Code lives in src/protocol/memcached/mod.rs (listener, item store, persistence, text and binary protocols) and src/protocol/memcached/meta.rs (meta commands).

Listener and threads

  • Default port 11211 (ProtocolHandler::default_port; memcached_port = Some(11211) in src/config.rs). (source: src/protocol/memcached/mod.rs, MemcachedHandler::default_port; src/config.rs)
  • MemcachedHandler::start accepts on the server runtime and hands each socket to one of worker_count() event-loop threads (memcached-<i>), each running its own single-threaded Tokio runtime, round robin. The count is SYNERGYDB_MEMCACHED_THREADS, else one per CPU, capped at 64. (source: src/protocol/memcached/mod.rs, start_workers, worker_count, STAT_BLOCKS)
  • With TLS configured (MemcachedHandler::with_tls), every connection is wrapped in TLS at accept (implicit TLS; plaintext clients cannot share the port). (source: src/protocol/memcached/mod.rs, MemcachedHandler::with_tls, accepted) Not verified: no Rust test covers Memcached over TLS.
  • Each connection reads into a 16 KiB buffer, parses every complete request in it, and answers them with one write. (source: src/protocol/memcached/mod.rs, MemcachedHandler::serve)
  • The server registers MemcachedHandler::shutdown_hook so a graceful shutdown drains pending writes before the storage engine closes. (source: src/server/mod.rs; src/protocol/memcached/mod.rs, shutdown_hook, Store::shutdown_drain)

Framing

The first byte of a connection picks the dialect for its whole life: 0x80 means binary, anything else means text (which includes the meta commands). (source: src/protocol/memcached/mod.rs, MemcachedHandler::serve)

Text protocol

Lines end in \n (an optional \r is stripped). A line longer than 1 MiB without a newline answers CLIENT_ERROR line too long and closes the connection. A request line shorter than 4 bytes including its line ending answers CLIENT_ERROR bad command line format, as memcached does. Storage commands are followed by a data block of the declared size plus \r\n. At most 24 tokens are read from a line. (source: src/protocol/memcached/mod.rs, text_step, MAX_LINE, MAX_TOKENS, BAD_FORMAT)

Binary protocol

24-byte header: magic 0x80, opcode, key length (u16 BE), extras length, data type, vbucket, total body length (u32 BE), opaque, CAS (u64 BE). A body length over 64 MiB answers status 0x0003 (too large) and closes the connection before any body is buffered. Extras plus key longer than the body answers 0x0004 (invalid) and closes. A key over 250 bytes answers 0x0004. (source: src/protocol/memcached/mod.rs, binary_step, MAX_MEMCACHED_BODY, MAX_KEY_LEN)

Meta protocol

mg, ms, md, ma, me are parsed by meta.rs, ported from memcached 1.6's proto_parser.c: flag parsing, the order of returned flags, which codes q hides, the stale, win and recache markers and the error strings follow memcached. mn is answered MN with the other text commands. A meta command may carry at most 20 tokens; an opaque (O) token at most 32 bytes; keys may be base64 (b). (source: src/protocol/memcached/meta.rs, module comment, preparse, MAX_TOKENS, MAX_OPAQUE)

Flags parsed by preparse: b (base64 key), N (vivify on miss, with TTL), T (TTL), R (recache threshold), v (return value), u (no LRU update), q (quiet), x (remove value on delete), F (client flags), C (compare CAS), E (explicit new CAS), M (mode), J (initial value for ma), D (delta for ma), I (invalidate, mark stale), and the return-only flags l, O, P, L, k, s, t, c, f, h. (source: src/protocol/memcached/meta.rs, preparse)

Commands

Text commands

Command Notes
get, gets Multi-key; gets returns the CAS token.
gat, gats Get and touch with a new exptime.
set, add, replace, append, prepend, cas noreply honoured.
delete noreply honoured.
incr, decr 64-bit unsigned counters; incr wraps, decr stops at 0.
touch  
flush_all [delay] [noreply] A delay schedules the flush on a spawned timer.
version Replies VERSION 1.6.0-synergydb.
verbosity Accepted, no effect.
cache_memlimit <MB> Changes the memory limit at runtime.
stats, stats reset General stats; stats settings returns only item_size_max; stats items, slabs, sizes, conns, extstore return an empty END. Other arguments answer ERROR.
mg, ms, md, ma, me, mn Meta commands (above).
quit Closes the connection.

Anything else answers ERROR. (source: src/protocol/memcached/mod.rs, text_step, text_other, text_get, text_store, VERSION)

The general stats reply includes pid, uptime, time, version, pointer_size, curr_connections, curr_items, bytes, limit_maxbytes, evictions, item_size_max, threads, and the per-command counters in ST_NAMES. (source: src/protocol/memcached/mod.rs, stat_pairs, ST_NAMES)

Binary opcodes

Opcode Name Handled as
0x00, 0x09, 0x0C, 0x0D GET, GETQ, GETK, GETKQ Read; Q variants are silent on a miss; K variants return the key.
0x1D, 0x1E, 0x23, 0x24 GAT, GATQ, GATK, GATKQ Read and touch (4-byte expiry extra required).
0x1C TOUCH  
0x01, 0x02, 0x03 SET, ADD, REPLACE  
0x11, 0x12, 0x13 SETQ, ADDQ, REPLACEQ  
0x0E, 0x0F, 0x19, 0x1A APPEND, PREPEND, APPENDQ, PREPENDQ  
0x04, 0x14 DELETE, DELETEQ Honours the request CAS.
0x05, 0x06, 0x15, 0x16 INCREMENT, DECREMENT, INCREMENTQ, DECREMENTQ  
0x07, 0x17 QUIT, QUITQ  
0x08, 0x18 FLUSH, FLUSHQ  
0x0A NOOP  
0x0B VERSION  
0x10 STAT  
0x1B VERBOSITY Accepted, no effect.
0x20 SASL_LIST_MECHS Replies PLAIN.
0x21 SASL_AUTH PLAIN only.
0x22 SASL_STEP PLAIN is single step: replies success if the connection is already authenticated, else an auth error.

Any other opcode answers status 0x0081 (unknown command). (source: src/protocol/memcached/mod.rs, binary_step)

Not implemented

  • Binary: the range and vbucket opcodes (0x30 and up, for example RGET, SET_VBUCKET, TAP), and 0x1F. (source: src/protocol/memcached/mod.rs, binary_step)
  • Text: slabs, lru_crawler, lru, watch, shutdown, debugtime, misbehave, extstore, stats detail, stats cachedump. These answer ERROR. Slab classes do not exist, so stats slabs and stats items are empty. (source: src/protocol/memcached/mod.rs, text_other)
  • SASL mechanisms other than PLAIN answer 0x0004 "Unsupported mechanism". (source: src/protocol/memcached/mod.rs, binary_step)

Authentication

The mode is read once from the environment by AuthMode::from_env:

Mode How it is selected Who starts authenticated
File SYNERGYDB_MEMCACHED_AUTH_FILE=<path> (checked first) Nobody. Credentials are user:password lines from the file, compared in constant time. An unreadable or malformed file leaves an empty list, so nobody can log in.
Users SYNERGYDB_MEMCACHED_AUTH = users, sasl, on, required, true or 1 Nobody. Credentials are SynergyDB roles.
Open SYNERGYDB_MEMCACHED_AUTH = open, off, none, no, false or 0; or, with the variable unset, SYNERGYDB_DEV_INSECURE_AUTH on Everybody.
LocalOnly (default) none of the above Loopback peers (127.0.0.1, ::1, IPv4-mapped loopback). Others must authenticate as SynergyDB roles.

(source: src/protocol/memcached/mod.rs, AuthMode, AuthMode::from_env, AuthMode::open_for, load_auth_file, ct_eq) Tested by default_mode_opens_loopback_only and explicit_modes in src/protocol/memcached/mod.rs, and unauthenticated_text_connection_is_refused in tests/protocol_memcached.rs.

SynergyDB-role logins go through verify_wire_credential("memcached", ...): a valid catalog password, and the role must be a superuser or a member of synergy_wire_memcached or synergy_wire_all (unless SYNERGYDB_WIRE_ACCESS=open). Failed logins are slowed after 5 failures per user name. (source: src/protocol/memcached/mod.rs, check_auth; src/auth/wire_auth.rs, verify_wire_credential, note_auth_result)

How a client authenticates:

  • Text. Until authenticated, the only accepted request is a set (key, flags and exptime ignored) whose data block is username password, memcached's -Y ASCII auth. Success answers STORED; failure CLIENT_ERROR authentication failure. Any other request answers CLIENT_ERROR unauthenticated. A token over 16,384 bytes answers CLIENT_ERROR auth token too long. (source: src/protocol/memcached/mod.rs, text_auth, serve)
  • Binary. SASL_AUTH with mechanism PLAIN and data [authzid]\0user\0password. Before login, only QUIT, QUITQ, NOOP, VERSION and STAT are served; everything else answers status 0x0020 "Authentication required". On a connection that starts open, the SASL opcodes answer "Unknown command", as memcached without SASL does. (source: src/protocol/memcached/mod.rs, binary_step)

Protected mode. Only when SYNERGYDB_DEV_INSECURE_AUTH is on and protected mode is on, a non-loopback client is refused with SERVER_ERROR DENIED SynergyDB is running in protected mode ... and the connection closes. In the default LocalOnly mode this check never fires; non-loopback clients are asked to authenticate instead. (source: src/protocol/memcached/mod.rs, handle_connection; src/auth/wire_auth.rs, protected_mode_refuses)

Item store

  • 64 shards (NUM_SHARDS), each a parking_lot::Mutex<Shard> over a HashMap<Vec<u8>, Entry>, selected by a randomly seeded hash of the key. A request never waits on disk. (source: src/protocol/memcached/mod.rs, Store, Store::lock)
  • Entry holds the data bytes, 32-bit client flags, absolute expiry (Unix seconds, 0 never), CAS, a recency stamp and state bits (fetched, active, stale, token sent, binary key). CAS values come from one store-wide counter. (source: src/protocol/memcached/mod.rs, Entry, Store::next_cas)
  • Exptime: 0 never expires; negative is already expired; up to 30 days is relative seconds; larger values are absolute Unix times, and an absolute time in the past is already expired. (source: src/protocol/memcached/mod.rs, exptime_to_abs) Tested by test_exptime_to_abs and cas_and_expiry.
  • Expired items are dropped when read, and a sweep every 30 s drops expired items nobody read again (and deletes their stored copy). (source: src/protocol/memcached/mod.rs, Store::sweep, SWEEP_INTERVAL)
  • Item size. An item may not exceed SYNERGYDB_MEMCACHED_MAX_ITEM_BYTES (default 1 MiB, memcached's -I 1m), counting key length plus 59 bytes of overhead. An oversized text set has its data swallowed and answers SERVER_ERROR object too large for cache. (source: src/protocol/memcached/mod.rs, DEFAULT_MAX_ITEM, ITEM_OVERHEAD, item_size, Store::fits) Tested by too_large_value_is_swallowed.
  • Memory limit and eviction. The limit is SYNERGYDB_MEMCACHED_MEMORY_MB (default 64, memcached's -m 64; 0 is unlimited; cache_memlimit changes it). Only an operation that took memory evicts. Eviction is a sampled LRU: the oldest item of the writing shard is compared with the oldest of up to 4 other shards that are free at that moment, and the oldest is evicted, repeatedly, until enough is freed. An active item (read twice since it was linked) gets a second chance. With SYNERGYDB_MEMCACHED_EVICTIONS=0|false|off, a store over the limit answers SERVER_ERROR out of memory storing object (memcached -M). An evicted item is also deleted from storage. (source: src/protocol/memcached/mod.rs, Store::out_of_memory, Shard::evict_oldest, Locked, EVICT_SAMPLE, DEFAULT_MEMORY_MB; docs/status/2026-11-30-memcached-lru.md) Tested by eviction_keeps_recent_and_hot_keys.

Storage mapping and durability

Records

Storage key Value
__memcached__:<key bytes> RECORD_V1 (byte 1), flags (u32 LE), absolute expiry (u64 LE), data bytes.
__memcached_meta__:imported Marker set once rows from earlier builds' SQL table were imported.
__memcached_meta__:mirror_clean Set by a graceful shutdown once the SQL mirror is complete; if missing at startup the mirror is rebuilt.

(source: src/protocol/memcached/mod.rs, PERSIST_PREFIX, IMPORT_MARKER, MIRROR_CLEAN_MARKER, Store::encode, Store::decode, Store::storage_key)

Keys and values are binary safe in these records. CAS values are not persisted; a restart gives items new CAS values. (source: src/protocol/memcached/mod.rs, Store::encode, Store::load)

SQL mirror

When persistence is on, the store also keeps a SQL table, created at startup if missing:

CREATE TABLE IF NOT EXISTS _memcached_store ("key" TEXT PRIMARY KEY, value TEXT, flags INTEGER)

A separate mirror thread applies committed keys every SYNERGYDB_MEMCACHED_MIRROR_MS (default 500 ms) in chunks of 256 keys, as DELETE ... WHERE "key" IN (...) followed by INSERT. Keys and values pass through String::from_utf8_lossy and NUL becomes U+FFFD, so the SQL view is not binary safe; the __memcached__: records are the source of truth. SYNERGYDB_MEMCACHED_SQL_MIRROR=0|false|off turns the mirror off. (source: src/protocol/memcached/mod.rs, Store::mirror_sql, Store::start_mirror, DEFAULT_MIRROR_MS, MIRROR_CHUNK, Store::load) Tested by sql_view_follows_wire_writes and the _memcached_store tests in tests/protocol_memcached.rs.

At startup, Store::load also imports rows from _memcached_store written by earlier builds (once, guarded by the import marker). Tested by rows_from_older_builds_are_served_on_the_wire.

Write-behind mode (default)

Each mutation marks its key dirty in its shard and increments a mutation sequence. A background writer thread waits SYNERGYDB_MEMCACHED_PERSIST_MS (default 10 ms) to gather writes, then writes the current state of every dirty key (a record, or a delete if the item is gone) with StorageEngine::write_batch in batches of up to 4,096 keys, one WAL group commit per batch. SYNERGYDB_MEMCACHED_WRITERS (default 1) splits shards across commit threads. (source: src/protocol/memcached/mod.rs, Store::start_writer, Store::persist_round, Store::write_shards, PERSIST_BATCH, DEFAULT_PERSIST_MS)

Replies do not wait for the writer. Back-pressure: when the durable copy trails by more than SYNERGYDB_MEMCACHED_MAX_LAG mutations (default 20,000), a connection waits until the lag is back under half of that. A kill -9 can therefore lose up to about the last batch window, and at most about max_lag mutations under load. (source: src/protocol/memcached/mod.rs, Store::limit_lag, DEFAULT_MAX_LAG)

Sync mode

SYNERGYDB_MEMCACHED_DURABILITY=sync (also strict, always) makes a connection wait, after processing one read buffer, until the writer has committed every mutation made so far (wait_committed). One group commit covers every waiting connection. Sync mode needs persistence on. (source: src/protocol/memcached/mod.rs, Store::new, Store::wait_committed, MemcachedHandler::serve)

Pure cache

SYNERGYDB_MEMCACHED_PERSIST=0|false|off gives a store with no durable copy: nothing is loaded or written. (source: src/protocol/memcached/mod.rs, MemcachedHandler::with_storage)

Startup

Store::load scans __memcached__: with the shared block cache bypassed (so the scan does not fill it), loads live items with their exact bytes, flags and absolute expiry, and deletes expired records. (source: src/protocol/memcached/mod.rs, Store::load; docs/status/2026-11-30-memcached-startup-memory.md) Tested by binary_value_flags_and_ttl_survive_restart, key_value_survives_restart and multiple_keys_survive_restart in tests/protocol_memcached.rs. The kill -9 restart check in memcached-text-binary-second-connection-restart.txt passed 9/23 in write-behind mode in the a3232c9 proof run (for example "2000 pipelined noreply sets all survived (0 of 2000)"); sync-mode results are in the README.

Error replies

Text reply When
ERROR Unknown command.
CLIENT_ERROR bad command line format Malformed line.
CLIENT_ERROR bad data chunk / bad command line termination Data block not followed by \r\n.
CLIENT_ERROR invalid exptime argument Unparsable exptime.
CLIENT_ERROR line too long Over 1 MiB with no newline (connection closed).
CLIENT_ERROR unauthenticated, authentication failure, auth token too long, bad authentication token format Auth gate.
SERVER_ERROR object too large for cache Item over the size limit.
SERVER_ERROR out of memory storing object At the limit with evictions off.
SERVER_ERROR DENIED ... Protected mode under the dev opt-in.
Binary status Meaning
0x0000 OK
0x0001 Key not found
0x0002 Key exists (CAS mismatch)
0x0003 Value too large
0x0004 Invalid arguments
0x0005 Item not stored
0x0006 Non-numeric value for incr/decr
0x0020 Authentication error
0x0081 Unknown command
0x0082 Out of memory

(source: src/protocol/memcached/mod.rs, status, text_step, text_store, text_auth, binary_step)

Configuration

Setting Default Effect
memcached_port (config) 11211 Port; a missing key in a config file turns the wire off.
SYNERGYDB_MEMCACHED_AUTH (loopback only) users or open; see Authentication.
SYNERGYDB_MEMCACHED_AUTH_FILE unset user:password file.
SYNERGYDB_MEMCACHED_PERSIST on 0 runs as a pure cache.
SYNERGYDB_MEMCACHED_DURABILITY write-behind sync waits for commit before replying.
SYNERGYDB_MEMCACHED_PERSIST_MS 10 Writer batch window.
SYNERGYDB_MEMCACHED_MAX_LAG 20000 Write-behind back-pressure bound (mutations).
SYNERGYDB_MEMCACHED_WRITERS 1 Commit threads (max 64).
SYNERGYDB_MEMCACHED_SQL_MIRROR on 0 turns off _memcached_store.
SYNERGYDB_MEMCACHED_MIRROR_MS 500 Mirror round interval.
SYNERGYDB_MEMCACHED_MEMORY_MB 64 Memory limit (0 unlimited).
SYNERGYDB_MEMCACHED_EVICTIONS on 0 refuses stores at the limit.
SYNERGYDB_MEMCACHED_MAX_ITEM_BYTES 1048576 Item size limit.
SYNERGYDB_MEMCACHED_THREADS CPU count Event-loop threads (max 64).

(source: src/protocol/memcached/mod.rs, Store::new, AuthMode::from_env, MemcachedHandler::with_storage, worker_count, Store::start_writer, Store::start_mirror)

Not verified: no Rust test sets SYNERGYDB_MEMCACHED_DURABILITY, SYNERGYDB_MEMCACHED_MAX_LAG, SYNERGYDB_MEMCACHED_WRITERS or SYNERGYDB_MEMCACHED_THREADS.

Audit

When the audit log is on, every request on an authenticated connection is classified (read: get, gets, gat, gats, mg, me; write: storage, delete, incr, decr, touch, ms, md, ma; admin: flush_all) and recorded, for text and binary alike. Loopback connections that started open are audited without a user identity. (source: src/protocol/memcached/mod.rs, audit_text, audit_binary; docs/status/2026-11-30-hipaa-audit-rls-tls.md)

Test coverage

Where What
src/protocol/memcached/mod.rs (12 tests) test_handler_creation, test_exptime_to_abs, test_parse_counter, text_pipeline_matches_memcached, cas_and_expiry, too_large_value_is_swallowed, binary_get_set_gat, test_stats, test_flush, default_mode_opens_loopback_only, explicit_modes, eviction_keeps_recent_and_hot_keys.
src/protocol/memcached/meta.rs (1 test) slab_classes_match_memcached_defaults: the slab class me (meta debug) reports for an item size.
tests/protocol_memcached.rs Handler construction, the _memcached_store table through QueryEngine, restart persistence, and wire tests: text_commands_answer_like_memcached, unauthenticated_text_connection_is_refused, binary_value_flags_and_ttl_survive_restart, sql_view_follows_wire_writes, rows_from_older_builds_are_served_on_the_wire.
Proof logs memcached-text-binary-second-connection-restart.txt, memcached-feature-matrix.txt (see the operator page for scores).

(source: the files named)

No Rust test covers binary SASL authentication, meta command parsing and replies (mg, ms, md, ma), or the write-behind lag bound; those rely on the Python differential suite.