xref: /memcached-1.4.29/doc/protocol.txt (revision 85ca98b5)
1Protocol
2--------
3
4Clients of memcached communicate with server through TCP connections.
5(A UDP interface is also available; details are below under "UDP
6protocol.") A given running memcached server listens on some
7(configurable) port; clients connect to that port, send commands to
8the server, read responses, and eventually close the connection.
9
10There is no need to send any command to end the session. A client may
11just close the connection at any moment it no longer needs it. Note,
12however, that clients are encouraged to cache their connections rather
13than reopen them every time they need to store or retrieve data.  This
14is because memcached is especially designed to work very efficiently
15with a very large number (many hundreds, more than a thousand if
16necessary) of open connections. Caching connections will eliminate the
17overhead associated with establishing a TCP connection (the overhead
18of preparing for a new connection on the server side is insignificant
19compared to this).
20
21There are two kinds of data sent in the memcache protocol: text lines
22and unstructured data.  Text lines are used for commands from clients
23and responses from servers. Unstructured data is sent when a client
24wants to store or retrieve data. The server will transmit back
25unstructured data in exactly the same way it received it, as a byte
26stream. The server doesn't care about byte order issues in
27unstructured data and isn't aware of them. There are no limitations on
28characters that may appear in unstructured data; however, the reader
29of such data (either a client or a server) will always know, from a
30preceding text line, the exact length of the data block being
31transmitted.
32
33Text lines are always terminated by \r\n. Unstructured data is _also_
34terminated by \r\n, even though \r, \n or any other 8-bit characters
35may also appear inside the data. Therefore, when a client retrieves
36data from a server, it must use the length of the data block (which it
37will be provided with) to determine where the data block ends, and not
38the fact that \r\n follows the end of the data block, even though it
39does.
40
41Keys
42----
43
44Data stored by memcached is identified with the help of a key. A key
45is a text string which should uniquely identify the data for clients
46that are interested in storing and retrieving it.  Currently the
47length limit of a key is set at 250 characters (of course, normally
48clients wouldn't need to use such long keys); the key must not include
49control characters or whitespace.
50
51Commands
52--------
53
54There are three types of commands.
55
56Storage commands (there are three: "set", "add" and "replace") ask the
57server to store some data identified by a key. The client sends a
58command line, and then a data block; after that the client expects one
59line of response, which will indicate success or faulure.
60
61Retrieval commands (there is only one: "get") ask the server to
62retrieve data corresponding to a set of keys (one or more keys in one
63request). The client sends a command line, which includes all the
64requested keys; after that for each item the server finds it sends to
65the client one response line with information about the item, and one
66data block with the item's data; this continues until the server
67finished with the "END" response line.
68
69All other commands don't involve unstructured data. In all of them,
70the client sends one command line, and expects (depending on the
71command) either one line of response, or several lines of response
72ending with "END" on the last line.
73
74A command line always starts with the name of the command, followed by
75parameters (if any) delimited by whitespace. Command names are
76lower-case and are case-sensitive.
77
78Expiration times
79----------------
80
81Some commands involve a client sending some kind of expiration time
82(relative to an item or to an operation requested by the client) to
83the server. In all such cases, the actual value sent may either be
84Unix time (number of seconds since January 1, 1970, as a 32-bit
85value), or a number of seconds starting from current time. In the
86latter case, this number of seconds may not exceed 60*60*24*30 (number
87of seconds in 30 days); if the number sent by a client is larger than
88that, the server will consider it to be real Unix time value rather
89than an offset from current time.
90
91
92Error strings
93-------------
94
95Each command sent by a client may be answered with an error string
96from the server. These error strings come in three types:
97
98- "ERROR\r\n"
99
100  means the client sent a nonexistent command name.
101
102- "CLIENT_ERROR <error>\r\n"
103
104  means some sort of client error in the input line, i.e. the input
105  doesn't conform to the protocol in some way. <error> is a
106  human-readable error string.
107
108- "SERVER_ERROR <error>\r\n"
109
110  means some sort of server error prevents the server from carrying
111  out the command. <error> is a human-readable error string. In cases
112  of severe server errors, which make it impossible to continue
113  serving the client (this shouldn't normally happen), the server will
114  close the connection after sending the error line. This is the only
115  case in which the server closes a connection to a client.
116
117
118In the descriptions of individual commands below, these error lines
119are not again specifically mentioned, but clients must allow for their
120possibility.
121
122
123Storage commands
124----------------
125
126First, the client sends a command line which looks like this:
127
128<command name> <key> <flags> <exptime> <bytes>\r\n
129
130- <command name> is "set", "add" or "replace"
131
132  "set" means "store this data".
133
134  "add" means "store this data, but only if the server *doesn't* already
135  hold data for this key".
136
137  "replace" means "store this data, but only if the server *does*
138  already hold data for this key".
139
140- <key> is the key under which the client asks to store the data
141
142- <flags> is an arbitrary 16-bit unsigned integer (written out in
143  decimal) that the server stores along with the data and sends back
144  when the item is retrieved. Clients may use this as a bit field to
145  store data-specific information; this field is opaque to the server.
146
147- <exptime> is expiration time. If it's 0, the item never expires
148  (although it may be deleted from the cache to make place for other
149  items). If it's non-zero (either Unix time or offset in seconds from
150  current time), it is guaranteed that clients will not be able to
151  retrieve this item after the expiration time arrives (measured by
152  server time).
153
154- <bytes> is the number of bytes in the data block to follow, *not*
155  including the delimiting \r\n. <bytes> may be zero (in which case
156  it's followed by an empty data block).
157
158After this line, the client sends the data block:
159
160<data block>\r\n
161
162- <data block> is a chunk of arbitrary 8-bit data of length <bytes>
163  from the previous line.
164
165After sending the command line and the data blockm the client awaits
166the reply, which may be:
167
168- "STORED\r\n", to indicate success.
169
170- "NOT_STORED\r\n" to indicate the data was not stored, but not
171because of an error. This normally means that either that the
172condition for an "add" or a "replace" command wasn't met, or that the
173item is in a delete queue (see the "delete" command below).
174
175
176Retrieval command:
177------------------
178
179The retrieval command looks like this:
180
181get <key>*\r\n
182
183- <key>* means one or more key strings separated by whitespace.
184
185After this command, the client expects zero or more items, each of
186which is received as a text line followed by a data block. After all
187the items have been transmitted, the server sends the string
188
189"END\r\n"
190
191to indicate the end of response.
192
193Each item sent by the server looks like this:
194
195VALUE <key> <flags> <bytes>\r\n
196<data block>\r\n
197
198- <key> is the key for the item being sent
199
200- <flags> is the flags value set by the storage command
201
202- <bytes> is the length of the data block to follow, *not* including
203  its delimiting \r\n
204
205- <data block> is the data for this item.
206
207If some of the keys appearing in a retrieval request are not sent back
208by the server in the item list this means that the server does not
209hold items with such keys (because they were never stored, or stored
210but deleted to make space for more items, or expired, or explicitly
211deleted by a client).
212
213
214
215Deletion
216--------
217
218The command "delete" allows for explicit deletion of items:
219
220delete <key> <time>\r\n
221
222- <key> is the key of the item the client wishes the server to delete
223
224- <time> is the amount of time in seconds (or Unix time until which)
225  the client wishes the server to refuse "add" and "replace" commands
226  with this key. For this amount of item, the item is put into a
227  delete queue, which means that it won't possible to retrieve it by
228  the "get" command, but "add" and "replace" command with this key
229  will also fail (the "set" command will succeed, however). After the
230  time passes, the item is finally deleted from server memory.
231
232  The parameter <time> is optional, and, if absent, defaults to 0
233  (which means that the item will be deleted immediately and further
234  storage commands with this key will succeed).
235
236The response line to this command can be one of:
237
238- "DELETED\r\n" to indicate success
239
240- "NOT_FOUND\r\n" to indicate that the item with this key was not
241  found.
242
243See the "flush_all" command below for immediate invalidation
244of all existing items.
245
246
247Increment/Decrement
248-------------------
249
250Commands "incr" and "decr" are used to change data for some item
251in-place, incrementing or decrementing it. The data for the item is
252treated as decimal representation of a 32-bit unsigned integer. If the
253current data value does not conform to such a representation, the
254commands behave as if the value were 0. Also, the item must already
255exist for incr/decr to work; these commands won't pretend that a
256non-existent key exists with value 0; instead, they will fail.
257
258The client sends the command line:
259
260incr <key> <value>\r\n
261
262or
263
264decr <key> <value>\r\n
265
266- <key> is the key of the item the client wishes to change
267
268- <value> is the amount by which the client wants to increase/decrease
269the item. It is a decimal representation of a 32-bit unsigned integer.
270
271The response will be one of:
272
273- "NOT_FOUND\r\n" to indicate the item with this value was not found
274
275- <value>\r\n , where <value> is the new value of the item's data,
276  after the increment/decrement operation was carried out.
277
278Note that underflow in the "decr" command is caught: if a client tries
279to decrease the value below 0, the new value will be 0. Overflow in
280the "incr" command is not checked.
281
282Note also that decrementing a number such that it loses length isn't
283guaranteed to decrement its returned length.  The number MAY be
284space-padded at the end, but this is purely an implementation
285optimization, so you also shouldn't rely on that.
286
287Statistics
288----------
289
290The command "stats" is used to query the server about statistics it
291maintains and other internal data. It has two forms. Without
292arguments:
293
294stats\r\n
295
296it causes the server to output general-purpose statistics and
297settings, documented below.  In the other form it has some arguments:
298
299stats <args>\r\n
300
301Depending on <args>, various internal data is sent by the server. The
302kinds of arguments and the data sent are not documented in this vesion
303of the protocol, and are subject to change for the convenience of
304memcache developers.
305
306
307General-purpose statistics
308--------------------------
309
310Upon receiving the "stats" command without arguments, the server sents
311a number of lines which look like this:
312
313STAT <name> <value>\r\n
314
315The server terminates this list with the line
316
317END\r\n
318
319In each line of statistics, <name> is the name of this statistic, and
320<value> is the data.  The following is the list of all names sent in
321response to the "stats" command, together with the type of the value
322sent for this name, and the meaning of the value.
323
324In the type column below, "32u" means a 32-bit unsigned integer, "64u"
325means a 64-bit unsigner integer. '32u:32u' means two 32-but unsigned
326integers separated by a colon.
327
328
329Name              Type     Meaning
330----------------------------------
331pid               32u      Process id of this server process
332uptime            32u      Number of seconds this server has been running
333time              32u      current UNIX time according to the server
334version           string   Version string of this server
335rusage_user       32u:32u  Accumulated user time for this process
336                           (seconds:microseconds)
337rusage_system     32u:32u  Accumulated system time for this process
338                           (seconds:microseconds)
339curr_items        32u      Current number of items stored by the server
340total_items       32u      Total number of items stored by this server
341                           ever since it started
342bytes             64u      Current number of bytes used by this server
343                           to store items
344curr_connections  32u      Number of open connections
345total_connections 32u      Total number of connections opened since
346                           the server started running
347connection_structures 32u  Number of connection structures allocated
348                           by the server
349cmd_get           64u      Cumulative number of retrieval requests
350cmd_set           64u      Cumulative number of storage requests
351get_hits          64u      Number of keys that have been requested and
352                           found present
353get_misses        64u      Number of items that have been requested
354                           and not found
355evictions         64u      Number of valid items removed from cache
356                           to free memory for new items
357bytes_read        64u      Total number of bytes read by this server
358                           from network
359bytes_written     64u      Total number of bytes sent by this server to
360                           network
361limit_maxbytes    32u      Number of bytes this server is allowed to
362                           use for storage.
363
364
365
366Other commands
367--------------
368
369"flush_all" is a command with an optional numeric argument. It always
370succeeds, and the server sends "OK\r\n" in response. Its effect is to
371invalidate all existing items immediately (by default) or after the
372expiration specified.  After invalidation none of the items will be returned
373in response to a retrieval command (unless it's stored again under the
374same key *after* flush_all has invalidated the items). flush_all doesn't
375actually free all the memory taken up by existing items; that will
376happen gradually as new items are stored. The most precise definition
377of what flush_all does is the following: it causes all items whose
378update time is earlier than the time at which flush_all was set to be
379executed to be ignored for retrieval purposes.
380
381The intent of flush_all with a delay, was that in a setting where you
382have a pool of memcached servers, and you need to flush all content,
383you have the option of not resetting all memcached servers at the
384same time (which could e.g. cause a spike in database load with all
385clients suddenly needing to recreate content that would otherwise
386have been found in the memcached daemon).
387
388The delay option allows you to have them reset in e.g. 10 second
389intervals (by passing 0 to the first, 10 to the second, 20 to the
390third, etc. etc.).
391
392
393"version" is a command with no arguments:
394
395version\r\n
396
397In response, the server sends
398
399"VERSION <version>\r\n", where <version> is the version string for the
400server.
401
402"verbosity" is a command with a numeric argument. It always
403succeeds, and the server sends "OK\r\n" in response. Its effect is to
404set the verbosity level of the logging output.
405
406"quit" is a command with no arguments:
407
408quit\r\n
409
410Upon receiving this command, the server closes the
411connection. However, the client may also simply close the connection
412when it no longer needs it, without issuing this command.
413
414
415UDP protocol
416------------
417
418For very large installations where the number of clients is high enough
419that the number of TCP connections causes scaling difficulties, there is
420also a UDP-based interface. The UDP interface does not provide guaranteed
421delivery, so should only be used for operations that aren't required to
422succeed; typically it is used for "get" requests where a missing or
423incomplete response can simply be treated as a cache miss.
424
425Each UDP datagram contains a simple frame header, followed by data in the
426same format as the TCP protocol described above. In the current
427implementation, requests must be contained in a single UDP datagram, but
428responses may span several datagrams. (The only common requests that would
429span multiple datagrams are huge multi-key "get" requests and "set"
430requests, both of which are more suitable to TCP transport for reliability
431reasons anyway.)
432
433The frame header is 8 bytes long, as follows (all values are 16-bit integers
434in network byte order, high byte first):
435
4360-1 Request ID
4372-3 Sequence number
4384-5 Total number of datagrams in this message
4396-7 Reserved for future use; must be 0
440
441The request ID is supplied by the client. Typically it will be a
442monotonically increasing value starting from a random seed, but the client
443is free to use whatever request IDs it likes. The server's response will
444contain the same ID as the incoming request. The client uses the request ID
445to differentiate between responses to outstanding requests if there are
446several pending from the same server; any datagrams with an unknown request
447ID are probably delayed responses to an earlier request and should be
448discarded.
449
450The sequence number ranges from 0 to n-1, where n is the total number of
451datagrams in the message. The client should concatenate the payloads of the
452datagrams for a given response in sequence number order; the resulting byte
453stream will contain a complete response in the same format as the TCP
454protocol (including terminating \r\n sequences).
455