doc/protocol.txt 1,927 lines View on github.com → Search inside
1Protocol2--------34Clients of memcached communicate with server through TCP connections.5(A UDP interface is also available; details are below under "UDP6protocol.") A given running memcached server listens on some7(configurable) port; clients connect to that port, send commands to8the server, read responses, and eventually close the connection.910There is no need to send any command to end the session. A client may11just close the connection at any moment it no longer needs it. Note,12however, that clients are encouraged to cache their connections rather13than reopen them every time they need to store or retrieve data.  This14is because memcached is especially designed to work very efficiently15with a very large number (many hundreds, more than a thousand if16necessary) of open connections. Caching connections will eliminate the17overhead associated with establishing a TCP connection (the overhead18of preparing for a new connection on the server side is insignificant19compared to this).2021There are two kinds of data sent in the memcache protocol: text lines22and unstructured data.  Text lines are used for commands from clients23and responses from servers. Unstructured data is sent when a client24wants to store or retrieve data. The server will transmit back25unstructured data in exactly the same way it received it, as a byte26stream. The server doesn't care about byte order issues in27unstructured data and isn't aware of them. There are no limitations on28characters that may appear in unstructured data; however, the reader29of such data (either a client or a server) will always know, from a30preceding text line, the exact length of the data block being31transmitted.3233Text lines are always terminated by \r\n. Unstructured data is _also_34terminated by \r\n, even though \r, \n or any other 8-bit characters35may also appear inside the data. Therefore, when a client retrieves36data from a server, it must use the length of the data block (which it37will be provided with) to determine where the data block ends, and not38the fact that \r\n follows the end of the data block, even though it39does.4041Keys42----4344Data stored by memcached is identified with the help of a key. A key45is a text string which should uniquely identify the data for clients46that are interested in storing and retrieving it.  Currently the47length limit of a key is set at 250 characters (of course, normally48clients wouldn't need to use such long keys); the key must not include49control characters or whitespace.5051Commands52--------5354There are three types of commands.5556Storage commands (there are six: "set", "add", "replace", "append"57"prepend" and "cas") ask the server to store some data identified by a58key. The client sends a command line, and then a data block; after59that the client expects one line of response, which will indicate60success or failure.6162Retrieval commands ("get", "gets", "gat", and "gats") ask the server to63retrieve data corresponding to a set of keys (one or more keys in one64request). The client sends a command line, which includes all the65requested keys; after that for each item the server finds it sends to66the client one response line with information about the item, and one67data block with the item's data; this continues until the server68finished with the "END" response line.6970All other commands don't involve unstructured data. In all of them,71the client sends one command line, and expects (depending on the72command) either one line of response, or several lines of response73ending with "END" on the last line.7475A command line always starts with the name of the command, followed by76parameters (if any) delimited by whitespace. Command names are77lower-case and are case-sensitive.7879Meta Commands80-------------8182Meta commands are a set of new ASCII-based commands. They follow the same83structure of the original commands but have a new flexible feature set.84Meta commands incorporate most features available in the binary protocol, as85well as a flag system to make the commands flexible rather than having a86large number of high level commands. These commands completely replace the87usage of basic Storage and Retrieval commands.8889Meta flags are not to be confused with client bitflags, which is an opaque90number passed by the client. Meta flags change how the command operates, but91they are not stored in cache.9293These work mixed with normal protocol commands on the same connection. All94existing commands continue to work. The meta commands will not replace95specialized commands that do not sit in the Storage or Retrieval categories96noted in the 'Commands' section above.9798All meta commands follow a basic syntax:99100<cm> <key> <datalen*> <flag1> <flag2> <...>\r\n101102Where <cm> is a 2 character command code.103<datalen> is only for commands with payloads, like set.104105Responses look like:106107<RC> <datalen*> <flag1> <flag2> <...>\r\n108109Where <RC> is a 2 character return code. The number of flags returned are110based off of the flags supplied.111112<datalen> is only for responses with payloads, with the return code 'VA'.113114Flags are single character codes, ie 'q' or 'k' or 'I', which adjust the115behavior of the command. If a flag requests a response flag (ie 't' for TTL116remaining), it is returned in the same order as they were in the original117command, though this is not strict.118119Flags are single character codes, ie 'q' or 'k' or 'O', which adjust the120behavior of a command. Flags may contain token arguments, which come after the121flag and before the next space or newline, ie 'Oopaque' or 'Kuserkey'. Flags122can return new data or reflect information, in the same order they were123supplied in the request. Sending an 't' flag with a get for an item with 20124seconds of TTL remaining, would return 't20' in the response.125126All commands accept a tokens 'P' and 'L' which are completely ignored. The127arguments to 'P' and 'L' can be used as hints or path specifications to a128proxy or router inbetween a client and a memcached daemon. For example, a129client may prepend a "path" in the key itself: "mg /path/foo v" or in a proxy130token: "mg foo Lpath/ v" - the proxy may then optionally remove or forward the131token to a memcached daemon, which will ignore them.132133Syntax errors are handled the same as noted under 'Error strings' section134below.135136For usage examples beyond basic syntax, please see the wiki:137https://github.com/memcached/memcached/wiki/MetaCommands138139Expiration times140----------------141142Some commands involve a client sending some kind of expiration time143(relative to an item or to an operation requested by the client) to144the server. In all such cases, the actual value sent may either be145Unix time (number of seconds since January 1, 1970, as a 32-bit146value), or a number of seconds starting from current time. In the147latter case, this number of seconds may not exceed 60*60*24*30 (number148of seconds in 30 days); if the number sent by a client is larger than149that, the server will consider it to be real Unix time value rather150than an offset from current time.151152Note that a TTL of 1 will sometimes immediately expire. Time is internally153updated on second boundaries, which makes expiration time roughly +/- 1s.154This more proportionally affects very low TTL's.155156Error strings157-------------158159Each command sent by a client may be answered with an error string160from the server. These error strings come in three types:161162- "ERROR\r\n"163164  means the client sent a nonexistent command name.165166- "CLIENT_ERROR <error>\r\n"167168  means some sort of client error in the input line, i.e. the input169  doesn't conform to the protocol in some way. <error> is a170  human-readable error string.171172- "SERVER_ERROR <error>\r\n"173174  means some sort of server error prevents the server from carrying175  out the command. <error> is a human-readable error string. In cases176  of severe server errors, which make it impossible to continue177  serving the client (this shouldn't normally happen), the server will178  close the connection after sending the error line. This is the only179  case in which the server closes a connection to a client.180181182In the descriptions of individual commands below, these error lines183are not again specifically mentioned, but clients must allow for their184possibility.185186Authentication187--------------188189Optional username/password token authentication (see -Y option). Used by190sending a fake "set" command with any key:191192set <key> <flags> <exptime> <bytes>\r\n193username password\r\n194195key, flags, and exptime are ignored for authentication. Bytes is the length196of the username/password payload.197198- "STORED\r\n" indicates success. After this point any command should work199  normally.200201- "CLIENT_ERROR [message]\r\n" will be returned if authentication fails for202  any reason.203204Storage commands205----------------206207First, the client sends a command line which looks like this:208209<command name> <key> <flags> <exptime> <bytes> [noreply]\r\n210cas <key> <flags> <exptime> <bytes> <cas unique> [noreply]\r\n211212- <command name> is "set", "add", "replace", "append" or "prepend"213214  "set" means "store this data".215216  "add" means "store this data, but only if the server *doesn't* already217  hold data for this key".218219  "replace" means "store this data, but only if the server *does*220  already hold data for this key".221222  "append" means "add this data to an existing key after existing data".223224  "prepend" means "add this data to an existing key before existing data".225226  The append and prepend commands do not accept flags or exptime.227  They update existing data portions, and ignore new flag and exptime228  settings.229230  "cas" is a check and set operation which means "store this data but231  only if no one else has updated since I last fetched it."232233- <key> is the key under which the client asks to store the data234235- <flags> is an arbitrary 16-bit unsigned integer (written out in236  decimal) that the server stores along with the data and sends back237  when the item is retrieved. Clients may use this as a bit field to238  store data-specific information; this field is opaque to the server.239  Note that in memcached 1.2.1 and higher, flags may be 32-bits, instead240  of 16, but you might want to restrict yourself to 16 bits for241  compatibility with older versions.242243- <exptime> is expiration time. If it's 0, the item never expires244  (although it may be deleted from the cache to make place for other245  items). If it's non-zero (either Unix time or offset in seconds from246  current time), it is guaranteed that clients will not be able to247  retrieve this item after the expiration time arrives (measured by248  server time). If a negative value is given the item is immediately249  expired.250251- <bytes> is the number of bytes in the data block to follow, *not*252  including the delimiting \r\n. <bytes> may be zero (in which case253  it's followed by an empty data block).254255- <cas unique> is a unique 64-bit value of an existing entry.256  Clients should use the value returned from the "gets" command257  when issuing "cas" updates.258259- "noreply" optional parameter instructs the server to not send the260  reply.  NOTE: if the request line is malformed, the server can't261  parse "noreply" option reliably.  In this case it may send the error262  to the client, and not reading it on the client side will break263  things.  Client should construct only valid requests.264265After this line, the client sends the data block:266267<data block>\r\n268269- <data block> is a chunk of arbitrary 8-bit data of length <bytes>270  from the previous line.271272After sending the command line and the data block the client awaits273the reply, which may be:274275- "STORED\r\n", to indicate success.276277- "NOT_STORED\r\n" to indicate the data was not stored, but not278because of an error. This normally means that the279condition for an "add" or a "replace" command wasn't met.280281- "EXISTS\r\n" to indicate that the item you are trying to store with282a "cas" command has been modified since you last fetched it.283284- "NOT_FOUND\r\n" to indicate that the item you are trying to store285with a "cas" command did not exist.286287288Retrieval command:289------------------290291The retrieval commands "get" and "gets" operate like this:292293get <key>*\r\n294gets <key>*\r\n295296- <key>* means one or more key strings separated by whitespace.297298After this command, the client expects zero or more items, each of299which is received as a text line followed by a data block. After all300the items have been transmitted, the server sends the string301302"END\r\n"303304to indicate the end of response.305306Each item sent by the server looks like this:307308VALUE <key> <flags> <bytes> [<cas unique>]\r\n309<data block>\r\n310311- <key> is the key for the item being sent312313- <flags> is the flags value set by the storage command314315- <bytes> is the length of the data block to follow, *not* including316  its delimiting \r\n317318- <cas unique> is a unique 64-bit integer that uniquely identifies319  this specific item.320321- <data block> is the data for this item.322323If some of the keys appearing in a retrieval request are not sent back324by the server in the item list this means that the server does not325hold items with such keys (because they were never stored, or stored326but deleted to make space for more items, or expired, or explicitly327deleted by a client).328329330Deletion331--------332333The command "delete" allows for explicit deletion of items:334335delete <key> [noreply]\r\n336337- <key> is the key of the item the client wishes the server to delete338339- "noreply" optional parameter instructs the server to not send the340  reply.  See the note in Storage commands regarding malformed341  requests.342343The response line to this command can be one of:344345- "DELETED\r\n" to indicate success346347- "NOT_FOUND\r\n" to indicate that the item with this key was not348  found.349350See the "flush_all" command below for immediate invalidation351of all existing items.352353354Increment/Decrement355-------------------356357Commands "incr" and "decr" are used to change data for some item358in-place, incrementing or decrementing it. The data for the item is359treated as decimal representation of a 64-bit unsigned integer.  If360the current data value does not conform to such a representation, the361incr/decr commands return an error (memcached <= 1.2.6 treated the362bogus value as if it were 0, leading to confusion). Also, the item363must already exist for incr/decr to work; these commands won't pretend364that a non-existent key exists with value 0; instead, they will fail.365366The client sends the command line:367368incr <key> <value> [noreply]\r\n369370or371372decr <key> <value> [noreply]\r\n373374- <key> is the key of the item the client wishes to change375376- <value> is the amount by which the client wants to increase/decrease377the item. It is a decimal representation of a 64-bit unsigned integer.378379- "noreply" optional parameter instructs the server to not send the380  reply.  See the note in Storage commands regarding malformed381  requests.382383The response will be one of:384385- "NOT_FOUND\r\n" to indicate the item with this value was not found386387- <value>\r\n , where <value> is the new value of the item's data,388  after the increment/decrement operation was carried out.389390Note that underflow in the "decr" command is caught: if a client tries391to decrease the value below 0, the new value will be 0.  Overflow in392the "incr" command will wrap around the 64 bit mark.393394Note also that decrementing a number such that it loses length isn't395guaranteed to decrement its returned length.  The number MAY be396space-padded at the end, but this is purely an implementation397optimization, so you also shouldn't rely on that.398399Touch400-----401402The "touch" command is used to update the expiration time of an existing item403without fetching it.404405touch <key> <exptime> [noreply]\r\n406407- <key> is the key of the item the client wishes the server to touch408409- <exptime> is expiration time. Works the same as with the update commands410  (set/add/etc). This replaces the existing expiration time. If an existing411  item were to expire in 10 seconds, but then was touched with an412  expiration time of "20", the item would then expire in 20 seconds.413414- "noreply" optional parameter instructs the server to not send the415  reply.  See the note in Storage commands regarding malformed416  requests.417418The response line to this command can be one of:419420- "TOUCHED\r\n" to indicate success421422- "NOT_FOUND\r\n" to indicate that the item with this key was not423  found.424425Get And Touch426-------------427428The "gat" and "gats" commands are used to fetch items and update the429expiration time of an existing items.430431gat <exptime> <key>*\r\n432gats <exptime> <key>*\r\n433434- <exptime> is expiration time.435436- <key>* means one or more key strings separated by whitespace.437438After this command, the client expects zero or more items, each of439which is received as a text line followed by a data block. After all440the items have been transmitted, the server sends the string441442"END\r\n"443444to indicate the end of response.445446Each item sent by the server looks like this:447448VALUE <key> <flags> <bytes> [<cas unique>]\r\n449<data block>\r\n450451- <key> is the key for the item being sent452453- <flags> is the flags value set by the storage command454455- <bytes> is the length of the data block to follow, *not* including456  its delimiting \r\n457458- <cas unique> is a unique 64-bit integer that uniquely identifies459  this specific item.460461- <data block> is the data for this item.462463Meta Debug464----------465466The meta debug command is a human readable dump of all available internal467metadata of an item, minus the value.468469me <key> <flag>\r\n470471- <key> means one key string.472- if <flag> is 'b', then <key> is a base64 encoded binary value. the response473  key will also be base64 encoded.474475The response looks like:476477ME <key> <k>=<v>*\r\n478479A miss looks like:480481EN\r\n482483Each of the keys and values are the internal data for the item.484485exp   = expiration time486la    = time in seconds since last access487cas   = CAS ID488fetch = whether an item has been fetched before489cls   = slab class id490size  = total size in bytes491492Others may be added.493494Meta Get495--------496497The meta get command is the generic command for retrieving key data from498memcached. Based on the flags supplied, it can replace all of the commands:499"get", "gets", "gat", "gats", "touch", as well as adding new options.500501mg <key> <flags>*\r\n502503- <key> means one key string. Unlike "get" metaget can only take a single key.504505- <flags> are a set of single character codes ended with a space or newline.506  flags may have token strings after the initial character.507508After this command, the client expects an item to be returned, received as a509text line followed by an optional data block.510511If a response line appearing in a retrieval request is not sent back512by the server this means that the server does not513have the item (because it was never stored, or stored514but deleted to make space for more items, or expired, or explicitly515deleted by a client).516517An item sent by the server looks like:518519VA <size> <flags>*\r\n520<data block>\r\n521522- <size> is the size of <data block> in bytes, minus the \r\n523524- <flags>* are flags returned by the server, based on the command flags.525  They are added in order specified by the flags sent.526527- <data block> is the data for this item. Note that the data block is528  optional, requiring the 'v' flag to be supplied.529530If the request did not ask for a value in the response (v) flag, the server531response looks like:532533HD <flags>*\r\n534535If the request resulted in a miss, the response looks like:536537EN\r\n538539Unless the (q) flag was supplied, which suppresses the status code for a miss.540541The flags used by the 'mg' command are:542543- b: interpret key as base64 encoded binary value544- c: return item cas token545- C(token): check CAS, do not send value if matches546- f: return client flags token547- h: return whether item has been hit before as a 0 or 1548- k: return key as a token549- l: return time since item was last accessed in seconds550- O(token): opaque value, consumes a token and copies back with response551- q: use noreply semantics for return codes.552- s: return item size token553- t: return item TTL remaining in seconds (-1 for unlimited)554- u: don't bump the item in the LRU555- v: return item value in <data block>556557These flags can modify the item:558- E(token): use token as new CAS value if item is modified559- N(token): vivify on miss, takes TTL as a argument560- R(token): if remaining TTL is less than token, win for recache561- T(token): update remaining TTL562563These extra flags can be added to the response:564- W: client has "won" the recache flag565- X: item is stale566- Z: item has already sent a winning flag567568The flags are now repeated with detailed information where useful:569570- b: interpret key as base64 encoded binary value571572This flag instructs memcached to run a base64 decoder on <key> before looking573it up. This allows storing and fetching of binary packed keys, so long as they574are sent to memcached in base64 encoding.575576If 'b' flag is sent in the response, and a key is returned via 'k', this577signals to the client that the key is base64 encoded binary.578579- C(token): check CAS value against item, remove 'v' flag if matches580581If a CAS token is supplied with C, and a 'v' flag is supplied, only return the582value if the CAS flag does NOT match. The response code will be "HD" if the583CAS does match, else "VA <size>" if the CAS does not match. This allows584conditionally fetching the value of an item only if it has changed.585586All other flags behave as normal, example: T(token) will update the TTL587regardless of if the CAS matches.588589- h: return whether item has been hit before as a 0 or 1590- l: return time since item was last accessed in seconds591592The above two flags return the value of "hit before?" and "last access time"593before the command was processed. Otherwise this would always show a 1 for594hit or always show an access time of "0" unless combined with the "u" flag.595596- O(token): opaque value, consumes a token and copies back with response597598The O(opaque) token is used by this and other commands to allow easier599pipelining of requests while saving bytes on the wire for responses. For600example: if pipelining three get commands together, you may not know which601response belongs to which without also retrieving the key. If the key is very602long this can generate a lot of traffic, especially if the data block is very603small. Instead, you can supply an "O" flag for each mg with tokens of "1" "2"604and "3", to match up responses to the request.605606Opaque tokens may be up to 32 bytes in length, and are a string similar to607keys.608609- q: use noreply semantics for return codes.610611Noreply is a method of reducing the amount of data sent back by memcached to612the client for normal responses. In the case of metaget, if an item is not613available the "VA" line is normally not sent, and the response is terminated by614"EN\r\n".615616With noreply enabled, the "EN\r\n" marker is suppressed. This allows you to617pipeline several mg's together and read all of the responses without the618"EN\r\n" lines in the middle.619620Errors are always returned.621622- u: don't bump the item in the LRU623624It is possible to access an item without causing it to be "bumped" to the head625of the LRU. This also avoids marking an item as being hit or updating its last626access time.627628- v: return item value in <data block>629630The data block for a metaget response is optional, requiring this flag to be631passed in. The response code also changes from "HD" to "VA <size>"632633These flags can modify the item:634- E(token): use token as new CAS value if item is modified635636Normally when an item is created it is given a CAS value from an internal637atomically incrementing counter. This allows overriding the CAS (8 byte638unsigned integer) with the specified value. This is useful for using an639external system to version cache data (row versions, clocks, etc).640641- N(token): vivify on miss, takes TTL as a argument642643Used to help with so called "dog piling" problems with recaching of popular644items. If supplied, and metaget does not find the item in cache, it will645create a stub item with the key and TTL as supplied. If such an item is646created a 'W' flag is added to the response to indicate to a client that they647have "won" the right to recache an item.648649The automatically created item has 0 bytes of data.650651Further requests will see a 'Z' flag to indicate that another client has652already received the win flag.653654Can be combined with CAS flags to gate the update further.655656- R(token): if token is less than remaining TTL win for recache657658Similar to and can be combined with 'N'. If the remaining TTL of an item is659below the supplied token, return a 'W' flag to indicate the client has "won"660the right to recache an item. This allows refreshing an item before it leads to661a miss.662663- T(token): update remaining TTL664665Similar to "touch" and "gat" commands, updates the remaining TTL of an item if666hit.667668These extra flags can be added to the response:669- W: client has "won" the recache flag670671When combined with N or R flags, a client may be informed they have "won"672ownership of a cache item. This allows a single client to be atomically673notified that it should cache or update an item. Further clients requesting674the item can use the existing data block (if valid or stale), retry, wait, or675take some other action while the item is missing.676677This is used when the act of recaching an item can cause undue load on another678system (CPU, database accesses, time, and so on).679680- X: item is stale681682Items can be marked as stale by the metadelete command. This indicates to the683client that an object needs to be updated, and that it should make a decision684o if potentially stale data is safe to use.685686This is used when you want to convince clients to recache an item, but it's687safe to use pre-existing data while the recache happens.688689- Z: item has already sent a winning flag690691When combined with the X flag, or the client N or R flags, this extra response692flag indicates to a client that a different client is responsible for693recaching this item. If there is data supplied it may use it, or the client694may decide to retry later or take some other action.695696Meta Set697--------698699The meta set command a generic command for storing data to memcached. Based700on the flags supplied, it can replace all storage commands (see token M) as701well as adds new options.702703ms <key> <datalen> <flags>*\r\n704705- <key> means one key string.706707- <datalen> is the length of the payload data.708709- <flags> are a set of single character codes ended with a space or newline.710  flags may have strings after the initial character.711712After this line, the client sends the data block:713714<data block>\r\n715716- <data block> is a chunk of arbitrary 8-bit data of length <datalen>717  from the previous line.718719After sending the command line and the data block the client awaits720the reply, which is of the format:721722<CD> <flags>*\r\n723724Where CD is one of:725726- "HD" (STORED), to indicate success.727728- "NS" (NOT_STORED), to indicate the data was not stored, but not729because of an error.730731- "EX" (EXISTS), to indicate that the item you are trying to store with732CAS semantics has been modified since you last fetched it.733734- "NF" (NOT_FOUND), to indicate that the item you are trying to store735with CAS semantics did not exist.736737The flags used by the 'ms' command are:738739- b: interpret key as base64 encoded binary value (see metaget)740- c: return CAS value if successfully stored.741- C(token): compare CAS value when storing item742- E(token): use token as new CAS value (see metaget for detail)743- F(token): set client flags to token (32 bit unsigned numeric)744- I: invalidate. set-to-invalid if supplied CAS is older than item's CAS745- k: return key as a token746- O(token): opaque value, consumes a token and copies back with response747- q: use noreply semantics for return codes748- s: return the size of the stored item on success (ie; new size on append)749- T(token): Time-To-Live for item, see "Expiration" above.750- M(token): mode switch to change behavior to add, replace, append, prepend751- N(token): if in append mode, autovivify on miss with supplied TTL752753The flags are now repeated with detailed information where useful:754755- c: returns the CAS value on successful storage. Will return 0 on error, but756  clients must not depend on the return value being zero. In future versions757this may return the current CAS value for "EX" return code conditions.758759- C(token): compare CAS value when storing item760761Similar to the basic "cas" command, only store item if the supplied token762matches the current CAS value of the item. When combined with the 'I' flag, a763CAS value that is _lower_ than the current value may be accepted, but the item764will be marked as "stale", returning the X flag with mget requests.765766- F(token): set client flags to token (32 bit unsigned numeric)767768Sets flags to 0 if not supplied.769770- I: invalid. set-to-invalid if CAS is older than it should be.771772Functional when combined with 'C' flag above.773774- O(token): opaque value, consumes a token and copies back with response775776See description under 'Meta Get'777778- q: use noreply semantics for return codes779780Noreply is a method of reducing the amount of data sent back by memcached to781the client for normal responses. In the case of metaset, a response that782would start with "HD" will not be sent. Any other code, such as "EX"783(EXISTS) will still be returned.784785Errors are always returned.786787- M(token): mode switch. Takes a single character for the mode.788789E: "add" command. LRU bump and return NS if item exists. Else790add.791A: "append" command. If item exists, append the new value to its data.792P: "prepend" command. If item exists, prepend the new value to its data.793R: "replace" command. Set only if item already exists.794S: "set" command. The default mode, added for completeness.795796The "cas" command is supplanted by specifying the cas value with the 'C' flag.797Append and Prepend modes will also respect a supplied cas value.798799- N(token): if in append mode, autovivify on miss with supplied TTL800801Append and Prepend modes normally ignore the T argument, as they cannot create802a new item on a miss. If N is supplied, and append reaches a miss, it will803create a new item seeded with the data from the append command. It uses the804TTL from N instead of T to be consistent with the usage of N in other805commands.806807Meta Delete808-----------809810The meta delete command allows for explicit deletion of items, as well as811marking items as "stale" to allow serving items as stale during revalidation.812813md <key> <flags>*\r\n814815- <key> means one key string.816817- <flags> are a set of single character codes ended with a space or newline.818  flags may have strings after the initial character.819820The response is in the format:821822<CD> <flags> <tokens>*\r\n823824Where CD is one of:825826- "HD" (DELETED), to indicate success827828- "NF" (NOT_FOUND), to indicate that the item with this key was not found.829830- "EX" (EXISTS), to indicate that the supplied CAS token does not match the831  stored item.832833The flags used by the 'md' command are:834835- b: interpret key as base64 encoded binary value (see metaget)836- C(token): compare CAS value837- E(token): use token as new CAS value (see metaget for detail)838- I: invalidate. mark as stale, bumps CAS.839- k: return key840- O(token): opaque to copy back.841- q: noreply842- T(token): updates TTL, only when paired with the 'I' flag843- x: removes the item value, but leaves the item.844845The flags are now repeated with detailed information where useful:846847- C(token): compare CAS value848849Can be used to only delete or mark-stale if a supplied CAS value matches.850851- I: invalidate. mark as stale, bumps CAS.852853Instead of removing an item, this will give the item a new CAS value and mark854it as stale. This means when it is later fetched by metaget, the client will855be supplied an 'X' flag to show the data is stale and needs to be recached.856857- O(token): opaque to copy back.858859See description under 'Meta Get'860861- q: noreply862863See description under 'Meta Set'. In the case of meta delete, this will hide864response lines with the code "DE". It will still return any other responses.865866- T(token): updates TTL, only when paired with the 'I' flag867868When marking an item as stale with 'I', the 'T' flag can be used to update the869TTL as well; limiting the amount of time an item will live while stale and870waiting to be recached.871872- x: removes the item value, but leaves the item.873874This deletes the value off of an item (by replacing it with an empty value875item atomically). Combined with I this can leave what is effectively a876tombstone of a previous value.877878Meta Arithmetic879---------------880881The meta arithmetic command allows for basic operations against numerical882values. This replaces the "incr" and "decr" commands. Values are unsigned88364bit integers. Decrementing will reach 0 rather than underflow. Incrementing884can overflow.885886ma <key> <flags>*\r\n887888- <key> means one key string.889890- <flags> are a set of single character codes ended with a space or newline.891  flags may have strings after the initial character.892893The response is in the format:894895<CD> <flags> <tokens>*\r\n896897Where CD is one of:898899- "HD" to indicate success900901- "NF" (NOT_FOUND), to indicate that the item with this key was not found.902903- "NS" (NOT_STORED), to indicate that the item was not created as requested904  after a miss.905906- "EX" (EXISTS), to indicate that the supplied CAS token does not match the907  stored item.908909If the 'v' flag is supplied, the response is formatted as:910911VA <size> <flags>*\r\n912<number>\r\n913914The flags used by the 'ma' command are:915916- b: interpret key as base64 encoded binary value (see metaget)917- C(token): compare CAS value (see mset)918- E(token): use token as new CAS value (see metaget for detail)919- N(token): auto create item on miss with supplied TTL920- J(token): initial value to use if auto created after miss (default 0)921- D(token): delta to apply (decimal unsigned 64-bit number, default 1)922- T(token): update TTL on success923- M(token): mode switch to change between incr and decr modes.924- O(token): opaque value, consumes a token and copies back with response925- q: use noreply semantics for return codes (see details under mset)926- t: return current TTL927- c: return current CAS value if successful.928- v: return new value929- k: return key as a token930931The flags are now repeated with detailed information where useful:932933- C(token): compare CAS value934935Can be used to only incr/decr if a supplied CAS value matches. A new CAS value936is generated after a delta is applied. Add the 'c' flag to get the new CAS937value after success.938939- N(token): auto create item on miss with supplied TTL940941Similar to mget, on a miss automatically create the item. A value can be942seeded using the J flag.943944- J(token): initial value945946An unsigned 64-bit integer which will be seeded as the value on a miss. Must be947combined with an N flag.948949- D(token): delta to apply950951An unsigned integer to either add or subtract from the currently stored952number.953954- T(token): update TTL955956On success, sets the remaining TTL to the supplied value.957958-M(token): mode switch. Takes a single character for the mode.959960I: Increment mode (default)961+: Alias for increment962D: Decrement mode963-: Alias for decrement964965Meta No-Op966----------967968The meta no-op command exists solely to return a static response code. It969takes no flags, no arguments.970971"mn\r\n"972973This returns the static response:974975"MN\r\n"976977This command is useful when used with the 'q' flag and pipelining commands.978For example, with 'mg' the response lines are blank on miss when the 'q' flag979is supplied. If pipelining several 'mg's together with noreply semantics, an980"mn\r\n" command can be tagged to the end of the chain, which will return an981"MN\r\n", signalling to a client that all previous commands have been982processed.983984Slabs Reassign985--------------986987NOTE: This command is subject to change as of this writing.988989The slabs reassign command is used to redistribute memory once a running990instance has hit its limit. It might be desirable to have memory laid out991differently than was automatically assigned after the server started.992993slabs reassign <source class> <dest class>\r\n994995- <source class> is an id number for the slab class to steal a page from996997A source class id of -1 means "pick from any valid class"998999- <dest class> is an id number for the slab class to move a page to10001001The response line could be one of:10021003- "OK" to indicate the page has been scheduled to move10041005- "BUSY [message]" to indicate a page is already being processed, try again1006  later.10071008- "BADCLASS [message]" a bad class id was specified10091010- "NOSPARE [message]" source class has no spare pages10111012- "NOTFULL [message]" dest class must be full to move new pages to it10131014- "UNSAFE [message]" source class cannot move a page right now10151016- "SAME [message]" must specify different source/dest ids.10171018Slabs Automove1019--------------10201021NOTE: This command is subject to change as of this writing.10221023The slabs automove command enables a background thread which decides on its1024own when to move memory between slab classes. Its implementation and options1025will likely be in flux for several versions. See the wiki/mailing list for1026more details.10271028The automover can be enabled or disabled at runtime with this command.10291030slabs automove <0|1|2>10311032- 0|1|2 is the indicator on whether to enable the slabs automover or not.10331034The response should always be "OK\r\n"10351036- <0> means to set the thread on standby10371038- <1> means to return pages to a global pool when there are more than 2 pages1039  worth of free chunks in a slab class. Pages are then re-assigned back into1040  other classes as-needed.10411042- <2> is a highly aggressive mode which causes pages to be moved every time1043  there is an eviction. It is not recommended to run for very long in this1044  mode unless your access patterns are very well understood.10451046LRU Tuning1047----------10481049Memcached supports multiple LRU algorithms, with a few tunables. Effort is1050made to have sane defaults however you are able to tune while the daemon is1051running.10521053The traditional model is "flat" mode, which is a single LRU chain per slab1054class. The newer (with `-o modern` or `-o lru_maintainer`) is segmented into1055HOT, WARM, COLD. There is also a TEMP LRU. See doc/new_lru.txt for details.10561057lru <tune|mode|temp_ttl> <option list>10581059- "tune" takes numeric arguments "percent hot", "percent warm",1060  "max hot factor", "max warm age factor". IE: "lru tune 10 25 0.1 2.0".1061  This would cap HOT_LRU at 10% of the cache, or tail is idle longer than1062  10% of COLD_LRU. WARM_LRU is up to 25% of cache, or tail is idle longer1063  than 2x COLD_LRU.10641065- "mode" <flat|segmented>: "flat" is traditional mode. "segmented" uses1066  HOT|WARM|COLD split. "segmented" mode requires `-o lru_maintainer` at start1067  time. If switching from segmented to flat mode, the background thread will1068  pull items from HOT|WARM into COLD queue.10691070- "temp_ttl" <ttl>: If TTL is less than zero, disable usage of TEMP_LRU. If1071  zero or above, items set with a TTL lower than this will go into TEMP_LRU1072  and be unevictable until they naturally expire or are otherwise deleted or1073  replaced.10741075The response line could be one of:10761077- "OK" to indicate a successful update of the settings.10781079- "ERROR [message]" to indicate a failure or improper arguments.10801081LRU_Crawler1082-----------10831084NOTE: This command (and related commands) are subject to change as of this1085writing.10861087The LRU Crawler is an optional background thread which will walk from the tail1088toward the head of requested slab classes, actively freeing memory for expired1089items. This is useful if you have a mix of items with both long and short1090TTL's, but aren't accessed very often. This system is not required for normal1091usage, and can add small amounts of latency and increase CPU usage.10921093lru_crawler <enable|disable>10941095- Enable or disable the LRU Crawler background thread.10961097The response line could be one of:10981099- "OK" to indicate the crawler has been started or stopped.11001101- "ERROR [message]" something went wrong while enabling or disabling.11021103lru_crawler sleep <microseconds>11041105- The number of microseconds to sleep in between each item checked for1106  expiration. Smaller numbers will obviously impact the system more.1107  A value of "0" disables the sleep, "1000000" (one second) is the max.11081109The response line could be one of:11101111- "OK"11121113- "CLIENT_ERROR [message]" indicating a format or bounds issue.11141115lru_crawler tocrawl <32u>11161117- The maximum number of items to inspect in a slab class per run request. This1118  allows you to avoid scanning all of very large slabs when it is unlikely to1119  find items to expire.11201121The response line could be one of:11221123- "OK"11241125- "CLIENT_ERROR [message]" indicating a format or bound issue.11261127lru_crawler crawl <classid,classid,classid|all>11281129- Takes a single, or a list of, numeric classids (ie: 1,3,10). This instructs1130  the crawler to start at the tail of each of these classids and run to the1131  head. The crawler cannot be stopped or restarted until it completes the1132  previous request.11331134  The special keyword "all" instructs it to crawl all slabs with items in1135  them.11361137The response line could be one of:11381139- "OK" to indicate successful launch.11401141- "BUSY [message]" to indicate the crawler is already processing a request.11421143- "BADCLASS [message]" to indicate an invalid class was specified.11441145lru_crawler metadump <classid,classid,classid|all|hash>11461147- Similar in function to the above "lru_crawler crawl" command, this function1148  outputs one line for every valid item found in the matching slab classes.1149  Similar to "cachedump", but does not lock the cache and can return all1150  items, not just 1MB worth.11511152  if "hash" is specified instead of a classid or "all", the crawler will dump1153  items by directly walking the hash table instead of the LRU's. This makes it1154  more likely all items will be visited once as LRU reordering and locking can1155  cause frequently accessed items to be missed.11561157  Lines are in "key=value key2=value2" format, with value being URI encoded1158  (ie: %20 for a space).11591160  The exact keys available are subject to change, but will include at least:11611162  "key", "exp" (expiration time), "la", (last access time), "cas",1163  "fetch" (if item has been fetched before).11641165The response line could be one of:11661167- "OK" to indicate successful launch.11681169- "BUSY [message]" to indicate the crawler is already processing a request.11701171- "BADCLASS [message]" to indicate an invalid class was specified.11721173lru_crawler mgdump <classid,classid,classid|all|hash>11741175- Similar in function to the above "lru_crawler crawl" command, this function1176  outputs one line for every valid item found in the matching slab classes.11771178  If "hash" is specified instead of a classid or "all", the crawler will dump1179  items by directly walking the hash table instead of the LRU's. This makes it1180  more likely all items will be visited once as LRU reordering and locking can1181  cause frequently accessed items to be missed.11821183  Lines are in a basic metaget format, like: "mg key\r\n". If a key is in1184  binary format: "mg base64encodedkey b\r\n"1185  A user may then take each line, append any flags they want, and run those1186  commands against the server to fetch exactly what they want to know.11871188The response line could be one of:11891190- "OK" to indicate successful launch.11911192- "BUSY [message]" to indicate the crawler is already processing a request.11931194- "BADCLASS [message]" to indicate an invalid class was specified.1195119611971198Watchers1199--------12001201Watchers are a way to connect to memcached and inspect what's going on1202internally. This is an evolving feature so new endpoints should show up over1203time.12041205watch <arg1> <arg2> <arg3>12061207possible arguments:1208fetchers1209mutations1210evictions1211connevents1212proxyreqs1213proxyevents1214proxyuser1215deletions12161217- Turn connection into a watcher. Options can be stacked and are1218  space-separated. Logs will be sent to the watcher until it disconnects.12191220The response line could be one of:12211222- "OK" to indicate the watcher is ready to send logs.12231224- "ERROR [message]" something went wrong while enabling.12251226The response format is in "key=value key2=value2" format, for easy parsing.1227Lines are prepending with "ts=" for a timestamp and "gid=" for a global ID1228number of the log line. Given how logs are collected internally they may be1229printed out of order. If this is important the GID may be used to put log1230lines back in order.12311232The value of keys (and potentially other things) are "URI encoded". Since most1233keys used conform to standard ASCII, this should have no effect. For keys with1234less standard or binary characters, "%NN"'s are inserted to represent the1235byte, ie: "n%2Cfoo" for "n,foo".12361237The arguments are:12381239- "fetchers": Currently emits logs every time an item is fetched internally.1240  This means a "set" command would also emit an item_get log, as it checks for1241  an item before replacing it. Multigets should also emit multiple lines.12421243- "mutations": Currently emits logs when an item is stored in most cases.1244  Shows errors for most cases when items cannot be stored.12451246- "evictions": Shows some information about items as they are evicted from the1247  cache. Useful in seeing if items being evicted were actually used, and which1248  keys are getting removed.12491250- "connevents": Emits logs when connections are opened and closed, i.e. when1251  clients connect or disconnect. For TCP transports, logs indicate the remote1252  address IP and port. Connection close events additionally supply a reason for1253  closing the connection. If TLS is enabled, this stream also contains1254  detailed TLS protocol errors.12551256- "proxyreqs": Emits detailed timing logs about requests/responses being1257  returned to a client while in proxy mode. The conditions which logs are1258  written here may be influenced by configuration.12591260- "proxyevents": Emits internal proxy errors and system events, such as1261  configuration reloads.12621263- "proxyuser": Emits log entries created from lua configuration files.12641265- "deletions": Emits logs when an item is successfully deleted from the1266  cache using `delete` or `md` commands. delete misses wouldn't be logged12671268Statistics1269----------12701271The command "stats" is used to query the server about statistics it1272maintains and other internal data. It has two forms. Without1273arguments:12741275stats\r\n12761277it causes the server to output general-purpose statistics and1278settings, documented below.  In the other form it has some arguments:12791280stats <args>\r\n12811282Depending on <args>, various internal data is sent by the server. The1283kinds of arguments and the data sent are not documented in this version1284of the protocol, and are subject to change for the convenience of1285memcache developers.128612871288General-purpose statistics1289--------------------------12901291Upon receiving the "stats" command without arguments, the server sends1292a number of lines which look like this:12931294STAT <name> <value>\r\n12951296The server terminates this list with the line12971298END\r\n12991300In each line of statistics, <name> is the name of this statistic, and1301<value> is the data.  The following is the list of all names sent in1302response to the "stats" command, together with the type of the value1303sent for this name, and the meaning of the value.13041305In the type column below, "32u" means a 32-bit unsigned integer, "64u"1306means a 64-bit unsigned integer. '32u.32u' means two 32-bit unsigned1307integers separated by a colon (treat this as a floating point number).13081309|-----------------------+---------+-------------------------------------------|1310| Name                  | Type    | Meaning                                   |1311|-----------------------+---------+-------------------------------------------|1312| pid                   | 32u     | Process id of this server process         |1313| uptime                | 32u     | Number of secs since the server started   |1314| time                  | 32u     | current UNIX time according to the server |1315| version               | string  | Version string of this server             |1316| pointer_size          | 32      | Default size of pointers on the host OS   |1317|                       |         | (generally 32 or 64)                      |1318| rusage_user           | 32u.32u | Accumulated user time for this process    |1319|                       |         | (seconds:microseconds)                    |1320| rusage_system         | 32u.32u | Accumulated system time for this process  |1321|                       |         | (seconds:microseconds)                    |1322| curr_items            | 64u     | Current number of items stored            |1323| total_items           | 64u     | Total number of items stored since        |1324|                       |         | the server started                        |1325| bytes                 | 64u     | Current number of bytes used              |1326|                       |         | to store items                            |1327| max_connections       | 32u     | Max number of simultaneous connections    |1328| curr_connections      | 32u     | Number of open connections                |1329| total_connections     | 32u     | Total number of connections opened since  |1330|                       |         | the server started running                |1331| rejected_connections  | 64u     | Conns rejected in maxconns_fast mode      |1332| connection_structures | 32u     | Number of connection structures allocated |1333|                       |         | by the server                             |1334| response_obj_oom      | 64u     | Connections closed by lack of memory      |1335| response_obj_count    | 64u     | Total response objects in use             |1336| response_obj_bytes    | 64u     | Total bytes used for resp. objects. is a  |1337|                       |         | subset of bytes from read_buf_bytes.      |1338| read_buf_count        | 64u     | Total read/resp buffers allocated         |1339| read_buf_bytes        | 64u     | Total read/resp buffer bytes allocated    |1340| read_buf_bytes_free   | 64u     | Total read/resp buffer bytes cached       |1341| read_buf_oom          | 64u     | Connections closed by lack of memory      |1342| reserved_fds          | 32u     | Number of misc fds used internally        |1343| proxy_conn_requests   | 64u     | Number of requests received by the proxy  |1344| proxy_conn_errors     | 64u     | Number of internal errors from proxy      |1345| proxy_conn_oom        | 64u     | Number of out of memory errors while      |1346|                       |         | serving proxy requests                    |1347| proxy_req_active      | 64u     | Number of in-flight proxy requests        |1348| cmd_get               | 64u     | Cumulative number of retrieval reqs       |1349| cmd_set               | 64u     | Cumulative number of storage reqs         |1350| cmd_flush             | 64u     | Cumulative number of flush reqs           |1351| cmd_touch             | 64u     | Cumulative number of touch reqs           |1352| get_hits              | 64u     | Number of keys that have been requested   |1353|                       |         | and found present                         |1354| get_misses            | 64u     | Number of items that have been requested  |1355|                       |         | and not found                             |1356| get_expired           | 64u     | Number of items that have been requested  |1357|                       |         | but had already expired.                  |1358| get_flushed           | 64u     | Number of items that have been requested  |1359|                       |         | but have been flushed via flush_all       |1360| delete_misses         | 64u     | Number of deletions reqs for missing keys |1361| delete_hits           | 64u     | Number of deletion reqs resulting in      |1362|                       |         | an item being removed.                    |1363| incr_misses           | 64u     | Number of incr reqs against missing keys. |1364| incr_hits             | 64u     | Number of successful incr reqs.           |1365| decr_misses           | 64u     | Number of decr reqs against missing keys. |1366| decr_hits             | 64u     | Number of successful decr reqs.           |1367| cas_misses            | 64u     | Number of CAS reqs against missing keys.  |1368| cas_hits              | 64u     | Number of successful CAS reqs.            |1369| cas_badval            | 64u     | Number of CAS reqs for which a key was    |1370|                       |         | found, but the CAS value did not match.   |1371| touch_hits            | 64u     | Number of keys that have been touched     |1372|                       |         | with a new expiration time                |1373| touch_misses          | 64u     | Number of items that have been touched    |1374|                       |         | and not found                             |1375| store_too_large       | 64u     | Number of rejected storage requests       |1376|                       |         | caused by attempting to write a value     |1377|                       |         | larger than the -I limit                  |1378| store_no_memory       | 64u     | Number of rejected storage requests       |1379|                       |         | caused by exhaustion of the -m memory     |1380|                       |         | limit (relevant when -M is used)          |1381| auth_cmds             | 64u     | Number of authentication commands         |1382|                       |         | handled, success or failure.              |1383| auth_errors           | 64u     | Number of failed authentications.         |1384| idle_kicks            | 64u     | Number of connections closed due to       |1385|                       |         | reaching their idle timeout.              |1386| evictions             | 64u     | Number of valid items removed from cache  |1387|                       |         | to free memory for new items              |1388| reclaimed             | 64u     | Number of times an entry was stored using |1389|                       |         | memory from an expired entry              |1390| bytes_read            | 64u     | Total number of bytes read by this server |1391|                       |         | from network                              |1392| bytes_written         | 64u     | Total number of bytes sent by this server |1393|                       |         | to network                                |1394| limit_maxbytes        | size_t  | Number of bytes this server is allowed to |1395|                       |         | use for storage.                          |1396| accepting_conns       | bool    | Whether or not server is accepting conns  |1397| listen_disabled_num   | 64u     | Number of times server has stopped        |1398|                       |         | accepting new connections (maxconns).     |1399| time_in_listen_disabled_us                                                  |1400|                       | 64u     | Number of microseconds in maxconns.       |1401| threads               | 32u     | Number of worker threads requested.       |1402|                       |         | (see doc/threads.txt)                     |1403| conn_yields           | 64u     | Number of times any connection yielded to |1404|                       |         | another due to hitting the -R limit.      |1405| hash_power_level      | 32u     | Current size multiplier for hash table    |1406| hash_bytes            | 64u     | Bytes currently used by hash tables       |1407| hash_is_expanding     | bool    | Indicates if the hash table is being      |1408|                       |         | grown to a new size                       |1409| expired_unfetched     | 64u     | Items pulled from LRU that were never     |1410|                       |         | touched by get/incr/append/etc before     |1411|                       |         | expiring                                  |1412| evicted_unfetched     | 64u     | Items evicted from LRU that were never    |1413|                       |         | touched by get/incr/append/etc.           |1414| evicted_active        | 64u     | Items evicted from LRU that had been hit  |1415|                       |         | recently but did not jump to top of LRU   |1416| slab_reassign_running | bool    | If a slab page is being moved             |1417| slabs_moved           | 64u     | Total slab pages moved                    |1418| crawler_reclaimed     | 64u     | Total items freed by LRU Crawler          |1419| crawler_items_checked | 64u     | Total items examined by LRU Crawler       |1420| lrutail_reflocked     | 64u     | Times LRU tail was found with active ref. |1421|                       |         | Items can be evicted to avoid OOM errors. |1422| moves_to_cold         | 64u     | Items moved from HOT/WARM to COLD LRU's   |1423| moves_to_warm         | 64u     | Items moved from COLD to WARM LRU         |1424| moves_within_lru      | 64u     | Items reshuffled within HOT or WARM LRU's |1425| direct_reclaims       | 64u     | Times worker threads had to directly      |1426|                       |         | reclaim or evict items.                   |1427| lru_crawler_starts    | 64u     | Times an LRU crawler was started          |1428| lru_maintainer_juggles                                                      |1429|                       | 64u     | Number of times the LRU bg thread woke up |1430| slab_global_page_pool | 32u     | Slab pages returned to global pool for    |1431|                       |         | reassignment to other slab classes.       |1432| slab_reassign_rescues | 64u     | Items rescued from eviction in page move  |1433| slab_reassign_chunk_rescues                                                 |1434|                       | 64u     | Individual sections of an item rescued    |1435|                       |         | during a page move.                       |1436| slab_reassign_inline_reclaim                                                |1437|                       | 64u     | Internal stat counter for when the page   |1438|                       |         | mover clears memory from the chunk        |1439|                       |         | freelist when it wasn't expecting to.     |1440| slab_reassign_busy_items                                                    |1441|                       | 64u     | Items busy during page move, requiring a  |1442|                       |         | retry before page can be moved.           |1443| slab_reassign_busy_nomem                                                    |1444|                       | 64u     | Times waiting for free slab memory before |1445|                       |         | being able to rescue valid items during   |1446|                       |         | a page move.                              |1447| slab_reassign_last_busy_status                                              |1448|                       | string  | Reason why an item was busy, causing the  |1449|                       |         | page mover to wait and retry later        |1450| slab_reassign_busy_deletes                                                  |1451|                       | 64u     | Items busy during page move, requiring    |1452|                       |         | deletion before page can be moved.        |1453| log_worker_dropped    | 64u     | Logs a worker never wrote due to full buf |1454| log_worker_written    | 64u     | Logs written by a worker, to be picked up |1455| log_watcher_skipped   | 64u     | Logs not sent to slow watchers.           |1456| log_watcher_sent      | 64u     | Logs written to watchers.                 |1457| log_watchers          | 64u     | Number of currently active watchers.      |1458| unexpected_napi_ids   | 64u     | Number of times an unexpected napi id is  |1459|                       |         | is received. See doc/napi_ids.txt         |1460| round_robin_fallback  | 64u     | Number of times napi id of 0 is received  |1461|                       |         | resulting in fallback to round robin      |1462|                       |         | thread selection. See doc/napi_ids.txt    |1463|-----------------------+---------+-------------------------------------------|14641465Settings statistics1466-------------------1467CAVEAT: This section describes statistics which are subject to change in the1468future.14691470The "stats" command with the argument of "settings" returns details of1471the settings of the running memcached.  This is primarily made up of1472the results of processing commandline options.14731474Note that these are not guaranteed to return in any specific order and1475this list may not be exhaustive.  Otherwise, this returns like any1476other stats command.14771478|-------------------+----------+----------------------------------------------|1479| Name              | Type     | Meaning                                      |1480|-------------------+----------+----------------------------------------------|1481| maxbytes          | size_t   | Maximum number of bytes allowed in the cache |1482| maxconns          | 32       | Maximum number of clients allowed.           |1483| tcpport           | 32       | TCP listen port.                             |1484| udpport           | 32       | UDP listen port.                             |1485| inter             | string   | Listen interface.                            |1486| verbosity         | 32       | 0 = none, 1 = some, 2 = lots                 |1487| oldest            | 32u      | Age of the oldest honored object.            |1488| evictions         | on/off   | When off, LRU evictions are disabled.        |1489| domain_socket     | string   | Path to the domain socket (if any).          |1490| umask             | 32 (oct) | umask for the creation of the domain socket. |1491| shutdown_command  | yes/no   | If shutdown admin command is enabled.        |1492| growth_factor     | float    | Chunk size growth factor.                    |1493| chunk_size        | 32       | Minimum space allocated for key+value+flags. |1494| num_threads       | 32       | Number of threads (including dispatch).      |1495| stat_key_prefix   | char     | Stats prefix separator character.            |1496| detail_enabled    | bool     | If yes, stats detail is enabled.             |1497| reqs_per_event    | 32       | Max num IO ops processed within an event.    |1498| cas_enabled       | bool     | When no, CAS is not enabled for this server. |1499| tcp_backlog       | 32       | TCP listen backlog.                          |1500| auth_enabled_sasl | yes/no   | SASL auth requested and enabled.             |1501| item_size_max     | size_t   | maximum item size                            |1502| maxconns_fast     | bool     | If fast disconnects are enabled              |1503| hashpower_init    | 32       | Starting size multiplier for hash table      |1504| slab_reassign     | bool     | Whether slab page reassignment is allowed    |1505| slab_automove     | bool     | Whether slab page automover is enabled       |1506| slab_automove_ratio                                                         |1507|                   | float    | Ratio limit between young/old slab classes   |1508| slab_automove_window                                                        |1509|                   | 32u      | Internal algo tunable for automove           |1510| slab_chunk_max    | 32       | Max slab class size (avoid unless necessary) |1511| hash_algorithm    | char     | Hash table algorithm in use                  |1512| lru_crawler       | bool     | Whether the LRU crawler is enabled           |1513| lru_crawler_sleep | 32       | Microseconds to sleep between LRU crawls     |1514| lru_crawler_tocrawl                                                         |1515|                   | 32u      | Max items to crawl per slab per run          |1516| lru_maintainer_thread                                                       |1517|                   | bool     | Split LRU mode and background threads        |1518| hot_lru_pct       | 32       | Pct of slab memory reserved for HOT LRU      |1519| warm_lru_pct      | 32       | Pct of slab memory reserved for WARM LRU     |1520| hot_max_factor    | float    | Set idle age of HOT LRU to COLD age * this   |1521| warm_max_factor   | float    | Set idle age of WARM LRU to COLD age * this  |1522| temp_lru          | bool     | If yes, items < temporary_ttl use TEMP_LRU   |1523| temporary_ttl     | 32u      | Items with TTL < this are marked  temporary  |1524| idle_time         | 0        | Drop connections that are idle this many     |1525|                   |          | seconds (0 disables)                         |1526| watcher_logbuf_size                                                         |1527|                   | 32u      | Size of internal (not socket) write buffer   |1528|                   |          | per active watcher connected.                |1529| worker_logbuf_size| 32u      | Size of internal per-worker-thread buffer    |1530|                   |          | which the background thread reads from.      |1531| read_obj_mem_limit| 32u      | Megabyte limit for conn. read/resp buffers.  |1532| track_sizes       | bool     | If yes, a "stats sizes" histogram is being   |1533|                   |          | dynamically tracked.                         |1534| inline_ascii_response                                                       |1535|                   | bool     | Does nothing as of 1.5.15                    |1536| drop_privileges   | bool     | If yes, and available, drop unused syscalls  |1537|                   |          | (see seccomp on Linux, pledge on OpenBSD)    |1538| proxy_enabled     | bool     | If proxy has been configured at start        |1539| proxy_uring_enabled                                                         |1540                    | bool     | If proxy is configured to use IO_URING.      |1541                    |          | NOTE: uring may be used if kernel too old    |1542| memory_file       | char     | Warm restart memory file path, if enabled    |1543| client_flags_size | 32u      | Size in bytes of client flags                |1544|-------------------+----------+----------------------------------------------|154515461547Item statistics1548---------------1549CAVEAT: This section describes statistics which are subject to change in the1550future.15511552The "stats" command with the argument of "items" returns information about1553item storage per slab class. The data is returned in the format:15541555STAT items:<slabclass>:<stat> <value>\r\n15561557The server terminates this list with the line15581559END\r\n15601561The slabclass aligns with class ids used by the "stats slabs" command. Where1562"stats slabs" describes size and memory usage, "stats items" shows higher1563level information.15641565The following item values are defined as of writing.15661567Name                   Meaning1568------------------------------1569number                 Number of items presently stored in this class. Expired1570                       items are not automatically excluded.1571number_hot             Number of items presently stored in the HOT LRU.1572number_warm            Number of items presently stored in the WARM LRU.1573number_cold            Number of items presently stored in the COLD LRU.1574number_temp            Number of items presently stored in the TEMPORARY LRU.1575age_hot                Age of the oldest item in HOT LRU.1576age_warm               Age of the oldest item in WARM LRU.1577age                    Age of the oldest item in the LRU.1578mem_requested          Number of bytes requested to be stored in this LRU[*]1579evicted                Number of times an item had to be evicted from the LRU1580                       before it expired.1581evicted_nonzero        Number of times an item which had an explicit expire1582                       time set had to be evicted from the LRU before it1583                       expired.1584evicted_time           Seconds since the last access for the most recent item1585                       evicted from this class. Use this to judge how1586                       recently active your evicted data is.1587outofmemory            Number of times the underlying slab class was unable to1588                       store a new item. This means you are running with -M or1589                       an eviction failed.1590tailrepairs            Number of times we self-healed a slab with a refcount1591                       leak. If this counter is increasing a lot, please1592                       report your situation to the developers.1593reclaimed              Number of times an entry was stored using memory from1594                       an expired entry.1595expired_unfetched      Number of expired items reclaimed from the LRU which1596                       were never touched after being set.1597evicted_unfetched      Number of valid items evicted from the LRU which were1598                       never touched after being set.1599evicted_active         Number of valid items evicted from the LRU which were1600                       recently touched but were evicted before being moved to1601                       the top of the LRU again.1602crawler_reclaimed      Number of items freed by the LRU Crawler.1603lrutail_reflocked      Number of items found to be refcount locked in the1604                       LRU tail.1605moves_to_cold          Number of items moved from HOT or WARM into COLD.1606moves_to_warm          Number of items moved from COLD to WARM.1607moves_within_lru       Number of times active items were bumped within1608                       HOT or WARM.1609direct_reclaims        Number of times worker threads had to directly pull LRU1610                       tails to find memory for a new item.1611hits_to_hot1612hits_to_warm1613hits_to_cold1614hits_to_temp           Number of get_hits to each sub-LRU.16151616Note this will only display information about slabs which exist, so an empty1617cache will return an empty set.16181619* Items are stored in a slab that is the same size or larger than the1620  item.  mem_requested shows the size of all items within a1621  slab. (total_chunks * chunk_size) - mem_requested shows memory1622  wasted in a slab class.  If you see a lot of waste, consider tuning1623  the slab factor.162416251626Item size statistics1627--------------------1628CAVEAT: This section describes statistics which are subject to change in the1629future.16301631The "stats" command with the argument of "sizes" returns information about the1632general size and count of all items stored in the cache.1633WARNING: In versions prior to 1.4.27 this command causes the cache server to1634lock while it iterates the items. 1.4.27 and greater are safe.16351636The data is returned in the following format:16371638STAT <size> <count>\r\n16391640The server terminates this list with the line16411642END\r\n16431644'size' is an approximate size of the item, within 32 bytes.1645'count' is the approximate amount of items that exist within that 32-byte1646range.16471648This is essentially a display of all of your items if there was a slab class1649for every 32 bytes. You can use this to determine if adjusting the slab growth1650factor would save memory overhead. For example: generating more classes in the1651lower range could allow items to fit more snugly into their slab classes, if1652most of your items are less than 200 bytes in size.16531654In 1.4.27 and after, this feature must be manually enabled.16551656It can be enabled at starttime with "-o track_sizes"16571658If disabled, "stats sizes" will return:16591660STAT sizes_status disabled\r\n16611662If an error happens, it will return:16631664STAT sizes_status error\r\n1665STAT sizes_error [error_message]\r\n16661667NOTE: From 1.4.27 to 1.6.24 this feature could be enabled or disabled at1668runtime via `stats sizes_enable` and `stats sizes_disable` - however this1669ability was not thread safe and could crash the server. While possible to fix,1670it would make the feature too slow to be usable.16711672The feature can still be enabled at start time via `-o track_sizes` and has a1673low overhead.16741675If you want to make a histogram of item sizes for a memcached instance that is1676already running, you can use `lru_crawler metadump` and process the output.1677This command does not block the server.16781679Slab statistics1680---------------1681CAVEAT: This section describes statistics which are subject to change in the1682future.16831684The "stats" command with the argument of "slabs" returns information about1685each of the slabs created by memcached during runtime. This includes per-slab1686information along with some totals. The data is returned in the format:16871688STAT <slabclass>:<stat> <value>\r\n1689STAT <stat> <value>\r\n16901691The server terminates this list with the line16921693END\r\n16941695|-----------------+----------------------------------------------------------|1696| Name            | Meaning                                                  |1697|-----------------+----------------------------------------------------------|1698| chunk_size      | The amount of space each chunk uses. One item will use   |1699|                 | one chunk of the appropriate size.                       |1700| chunks_per_page | How many chunks exist within one page. A page by         |1701|                 | default is less than or equal to one megabyte in size.   |1702|                 | Slabs are allocated by page, then broken into chunks.    |1703| total_pages     | Total number of pages allocated to the slab class.       |1704| total_chunks    | Total number of chunks allocated to the slab class.      |1705| get_hits        | Total number of get requests serviced by this class.     |1706| cmd_set         | Total number of set requests storing data in this class. |1707| delete_hits     | Total number of successful deletes from this class.      |1708| incr_hits       | Total number of incrs modifying this class.              |1709| decr_hits       | Total number of decrs modifying this class.              |1710| cas_hits        | Total number of CAS commands modifying this class.       |1711| cas_badval      | Total number of CAS commands that failed to modify a     |1712|                 | value due to a bad CAS id.                               |1713| touch_hits      | Total number of touches serviced by this class.          |1714| used_chunks     | How many chunks have been allocated to items.            |1715| free_chunks     | Chunks not yet allocated to items, or freed via delete.  |1716| free_chunks_end | Number of free chunks at the end of the last allocated   |1717|                 | page.                                                    |1718| active_slabs    | Total number of slab classes allocated.                  |1719| total_malloced  | Total amount of memory allocated to slab pages.          |1720|-----------------+----------------------------------------------------------|172117221723Connection statistics1724---------------------1725The "stats" command with the argument of "conns" returns information1726about currently active connections and about sockets that are listening1727for new connections. The data is returned in the format:17281729STAT <file descriptor>:<stat> <value>\r\n17301731The server terminates this list with the line17321733END\r\n17341735The following "stat" keywords may be present:17361737|---------------------+------------------------------------------------------|1738| Name                | Meaning                                              |1739|---------------------+------------------------------------------------------|1740| addr                | The address of the remote side. For listening        |1741|                     | sockets this is the listen address. Note that some   |1742|                     | socket types (such as UNIX-domain) don't have        |1743|                     | meaningful remote addresses.                         |1744| listen_addr         | The address of the server. This field is absent      |1745|                     | for listening sockets.                               |1746| state               | The current state of the connection. See below.      |1747| secs_since_last_cmd | The number of seconds since the most recently        |1748|                     | issued command on the connection. This measures      |1749|                     | the time since the start of the command, so if       |1750|                     | "state" indicates a command is currently executing,  |1751|                     | this will be the number of seconds the current       |1752|                     | command has been running.                            |1753|---------------------+------------------------------------------------------|17541755The value of the "state" stat may be one of the following:17561757|----------------+-----------------------------------------------------------|1758| Name           | Meaning                                                   |1759|----------------+-----------------------------------------------------------|1760| conn_closing   | Shutting down the connection.                             |1761| conn_listening | Listening for new connections or a new UDP request.       |1762| conn_mwrite    | Writing a complex response, e.g., to a "get" command.     |1763| conn_new_cmd   | Connection is being prepared to accept a new command.     |1764| conn_nread     | Reading extended data, typically for a command such as    |1765|                | "set" or "put".                                           |1766| conn_parse_cmd | The server has received a command and is in the middle    |1767|                | of parsing it or executing it.                            |1768| conn_read      | Reading newly-arrived command data.                       |1769| conn_swallow   | Discarding excess input, e.g., after an error has         |1770|                | occurred.                                                 |1771| conn_waiting   | A partial command has been received and the server is     |1772|                | waiting for the rest of it to arrive (note the difference |1773|                | between this and conn_nread).                             |1774| conn_write     | Writing a simple response (anything that doesn't involve  |1775|                | sending back multiple lines of response data).            |1776|----------------+-----------------------------------------------------------|17771778TLS statistics1779--------------17801781TLS is a compile-time opt-in feature available in versions 1.5.13 and later.1782When compiled with TLS support and TLS termination is enabled at runtime, the1783following additional statistics are available via the "stats" command.17841785|--------------------------------+----------+--------------------------------|1786| Name                           | Type     | Meaning                        |1787|--------------------------------+----------+--------------------------------|1788| ssl_handshake_errors           | 64u      | Number of times the server has |1789|                                |          | encountered an OpenSSL error   |1790|                                |          | during handshake (SSL_accept). |1791| ssl_proto_errors               | 64u      | Number of times a client has   |1792|                                |          | seen a fatal TLS protocol error|1793| ssl_min_version                | char     | Minimum supported TLS version  |1794|                                |          | for client handshakes.         |1795| ssl_new_sessions               | 64u      | When SSL session caching is    |1796|                                |          | enabled, the number of newly   |1797|                                |          | created server-side sessions.  |1798|                                |          | Available only when compiled   |1799|                                |          | with OpenSSL 1.1.1 or newer.   |1800| time_since_server_cert_refresh | 32u      | Number of seconds that have    |1801|                                |          | elapsed since the last time    |1802|                                |          | certs were reloaded from disk. |1803|--------------------------------+----------+--------------------------------|180418051806Other commands1807--------------18081809"flush_all" is a command with an optional numeric argument. It always1810succeeds, and the server sends "OK\r\n" in response (unless "noreply"1811is given as the last parameter). Its effect is to invalidate all1812existing items immediately (by default) or after the expiration1813specified.  After invalidation none of the items will be returned in1814response to a retrieval command (unless it's stored again under the1815same key *after* flush_all has invalidated the items). flush_all1816doesn't actually free all the memory taken up by existing items; that1817will happen gradually as new items are stored. The most precise1818definition of what flush_all does is the following: it causes all1819items whose update time is earlier than the time at which flush_all1820was set to be executed to be ignored for retrieval purposes.18211822The intent of flush_all with a delay, was that in a setting where you1823have a pool of memcached servers, and you need to flush all content,1824you have the option of not resetting all memcached servers at the1825same time (which could e.g. cause a spike in database load with all1826clients suddenly needing to recreate content that would otherwise1827have been found in the memcached daemon).18281829The delay option allows you to have them reset in e.g. 10 second1830intervals (by passing 0 to the first, 10 to the second, 20 to the1831third, etc. etc.).18321833"cache_memlimit" is a command with a numeric argument. This allows runtime1834adjustments of the cache memory limit. It returns "OK\r\n" or an error (unless1835"noreply" is given as the last parameter). If the new memory limit is higher1836than the old one, the server may start requesting more memory from the OS. If1837the limit is lower, and slabs_reassign+automove are enabled, free memory may1838be released back to the OS asynchronously.18391840The argument is in megabytes, not bytes. Input gets multiplied out into1841megabytes internally.18421843"shutdown" is a command with an optional argument used to stop memcached with1844a kill signal. By default, "shutdown" alone raises SIGINT, though "graceful"1845may be specified as the single argument to instead trigger a graceful shutdown1846with SIGUSR1. The shutdown command is disabled by default, and can be enabled1847with the -A/--enable-shutdown flag.18481849"version" is a command with no arguments:18501851version\r\n18521853In response, the server sends18541855"VERSION <version>\r\n", where <version> is the version string for the1856server.18571858"verbosity" is a command with a numeric argument. It always succeeds,1859and the server sends "OK\r\n" in response (unless "noreply" is given1860as the last parameter). Its effect is to set the verbosity level of1861the logging output.18621863"quit" is a command with no arguments:18641865quit\r\n18661867Upon receiving this command, the server closes the1868connection. However, the client may also simply close the connection1869when it no longer needs it, without issuing this command.18701871Security restrictions1872---------------------18731874In the debug build the following commands are available for testing the1875security restrictions:18761877"misbehave" is a command with no arguments:18781879misbehave\r\n18801881This command causes the worker thread to attempt a) opening a new socket, and1882b) executing a shell command. If either one is successful, an error is1883returned. Otherwise memcached returns OK.1884The check is available only in Linux builds with seccomp enabled.188518861887UDP protocol1888------------18891890For very large installations where the number of clients is high enough1891that the number of TCP connections causes scaling difficulties, there is1892also a UDP-based interface. The UDP interface does not provide guaranteed1893delivery, so should only be used for operations that aren't required to1894succeed; typically it is used for "get" requests where a missing or1895incomplete response can simply be treated as a cache miss.18961897Each UDP datagram contains a simple frame header, followed by data in the1898same format as the TCP protocol described above. In the current1899implementation, requests must be contained in a single UDP datagram, but1900responses may span several datagrams. (The only common requests that would1901span multiple datagrams are huge multi-key "get" requests and "set"1902requests, both of which are more suitable to TCP transport for reliability1903reasons anyway.)19041905The frame header is 8 bytes long, as follows (all values are 16-bit integers1906in network byte order, high byte first):190719080-1 Request ID19092-3 Sequence number19104-5 Total number of datagrams in this message19116-7 Reserved for future use; must be 019121913The request ID is supplied by the client. Typically it will be a1914monotonically increasing value starting from a random seed, but the client1915is free to use whatever request IDs it likes. The server's response will1916contain the same ID as the incoming request. The client uses the request ID1917to differentiate between responses to outstanding requests if there are1918several pending from the same server; any datagrams with an unknown request1919ID are probably delayed responses to an earlier request and should be1920discarded.19211922The sequence number ranges from 0 to n-1, where n is the total number of1923datagrams in the message. The client should concatenate the payloads of the1924datagrams for a given response in sequence number order; the resulting byte1925stream will contain a complete response in the same format as the TCP1926protocol (including terminating \r\n sequences).

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings