summaryrefslogtreecommitdiff
path: root/doc/protocol.txt
blob: cd476dbdbe55026bd0d2998e9cdb2d5741a100c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
Protocol
--------

Clients of memcached communicate with server through TCP connections.
(A UDP interface is also available; details are below under "UDP
protocol.") A given running memcached server listens on some
(configurable) port; clients connect to that port, send commands to
the server, read responses, and eventually close the connection.

There is no need to send any command to end the session. A client may
just close the connection at any moment it no longer needs it. Note,
however, that clients are encouraged to cache their connections rather
than reopen them every time they need to store or retrieve data.  This
is because memcached is especially designed to work very efficiently
with a very large number (many hundreds, more than a thousand if
necessary) of open connections. Caching connections will eliminate the
overhead associated with establishing a TCP connection (the overhead
of preparing for a new connection on the server side is insignificant
compared to this).

There are two kinds of data sent in the memcache protocol: text lines
and unstructured data.  Text lines are used for commands from clients
and responses from servers. Unstructured data is sent when a client
wants to store or retrieve data. The server will transmit back
unstructured data in exactly the same way it received it, as a byte
stream. The server doesn't care about byte order issues in
unstructured data and isn't aware of them. There are no limitations on
characters that may appear in unstructured data; however, the reader
of such data (either a client or a server) will always know, from a
preceding text line, the exact length of the data block being
transmitted.

Text lines are always terminated by \r\n. Unstructured data is _also_
terminated by \r\n, even though \r, \n or any other 8-bit characters
may also appear inside the data. Therefore, when a client retrieves
data from a server, it must use the length of the data block (which it
will be provided with) to determine where the data block ends, and not
the fact that \r\n follows the end of the data block, even though it
does.

Keys
----

Data stored by memcached is identified with the help of a key. A key
is a text string which should uniquely identify the data for clients
that are interested in storing and retrieving it.  Currently the
length limit of a key is set at 250 characters (of course, normally
clients wouldn't need to use such long keys); the key must not include
control characters or whitespace.

Commands
--------

There are three types of commands.

Storage commands (there are six: "set", "add", "replace", "append"
"prepend" and "cas") ask the server to store some data identified by a
key. The client sends a command line, and then a data block; after
that the client expects one line of response, which will indicate
success or failure.

Retrieval commands ("get", "gets", "gat", and "gats") ask the server to
retrieve data corresponding to a set of keys (one or more keys in one
request). The client sends a command line, which includes all the
requested keys; after that for each item the server finds it sends to
the client one response line with information about the item, and one
data block with the item's data; this continues until the server
finished with the "END" response line.

All other commands don't involve unstructured data. In all of them,
the client sends one command line, and expects (depending on the
command) either one line of response, or several lines of response
ending with "END" on the last line.

A command line always starts with the name of the command, followed by
parameters (if any) delimited by whitespace. Command names are
lower-case and are case-sensitive.

Meta Commands
-------------

Meta commands are a set of new ASCII-based commands. They follow the same
structure of the original commands but have a new flexible feature set.
Meta commands incorporate most features available in the binary protocol, as
well as a flag system to make the commands flexible rather than having a
large number of high level commands. These commands completely replace the
usage of basic Storage and Retrieval commands.

Meta flags are not to be confused with client bitflags, which is an opaque
number passed by the client. Meta flags change how the command operates, but
they are not stored in cache.

These work mixed with normal protocol commands on the same connection. All
existing commands continue to work. The meta commands will not replace
specialized commands that do not sit in the Storage or Retrieval categories
noted in the 'Commands' section above.

All meta commands follow a basic syntax:

<cm> <key> <datalen*> <flag1> <flag2> <...>\r\n

Where <cm> is a 2 character command code.
<datalen> is only for commands with payloads, like set.

Responses look like:

<RC> <datalen*> <flag1> <flag2> <...>\r\n

Where <RC> is a 2 character return code. The number of flags returned are
based off of the flags supplied.

<datalen> is only for responses with payloads, with the return code 'VA'.

Flags are single character codes, ie 'q' or 'k' or 'I', which adjust the
behavior of the command. If a flag requests a response flag (ie 't' for TTL
remaining), it is returned in the same order as they were in the original
command, though this is not strict.

Flags are single character codes, ie 'q' or 'k' or 'O', which adjust the
behavior of a command. Flags may contain token arguments, which come after the
flag and before the next space or newline, ie 'Oopaque' or 'Kuserkey'. Flags
can return new data or reflect information, in the same order they were
supplied in the request. Sending an 't' flag with a get for an item with 20
seconds of TTL remaining, would return 't20' in the response.

All commands accept a tokens 'P' and 'L' which are completely ignored. The
arguments to 'P' and 'L' can be used as hints or path specifications to a
proxy or router inbetween a client and a memcached daemon. For example, a
client may prepend a "path" in the key itself: "mg /path/foo v" or in a proxy
token: "mg foo Lpath/ v" - the proxy may then optionally remove or forward the
token to a memcached daemon, which will ignore them.

Syntax errors are handled the same as noted under 'Error strings' section
below.

For usage examples beyond basic syntax, please see the wiki:
https://github.com/memcached/memcached/wiki/MetaCommands

Expiration times
----------------

Some commands involve a client sending some kind of expiration time
(relative to an item or to an operation requested by the client) to
the server. In all such cases, the actual value sent may either be
Unix time (number of seconds since January 1, 1970, as a 32-bit
value), or a number of seconds starting from current time. In the
latter case, this number of seconds may not exceed 60*60*24*30 (number
of seconds in 30 days); if the number sent by a client is larger than
that, the server will consider it to be real Unix time value rather
than an offset from current time.

Note that a TTL of 1 will sometimes immediately expire. Time is internally
updated on second boundaries, which makes expiration time roughly +/- 1s.
This more proportionally affects very low TTL's.

Error strings
-------------

Each command sent by a client may be answered with an error string
from the server. These error strings come in three types:

- "ERROR\r\n"

  means the client sent a nonexistent command name.

- "CLIENT_ERROR <error>\r\n"

  means some sort of client error in the input line, i.e. the input
  doesn't conform to the protocol in some way. <error> is a
  human-readable error string.

- "SERVER_ERROR <error>\r\n"

  means some sort of server error prevents the server from carrying
  out the command. <error> is a human-readable error string. In cases
  of severe server errors, which make it impossible to continue
  serving the client (this shouldn't normally happen), the server will
  close the connection after sending the error line. This is the only
  case in which the server closes a connection to a client.


In the descriptions of individual commands below, these error lines
are not again specifically mentioned, but clients must allow for their
possibility.

Authentication
--------------

Optional username/password token authentication (see -Y option). Used by
sending a fake "set" command with any key:

set <key> <flags> <exptime> <bytes>\r\n
username password\r\n

key, flags, and exptime are ignored for authentication. Bytes is the length
of the username/password payload.

- "STORED\r\n" indicates success. After this point any command should work
  normally.

- "CLIENT_ERROR [message]\r\n" will be returned if authentication fails for
  any reason.

Storage commands
----------------

First, the client sends a command line which looks like this:

<command name> <key> <flags> <exptime> <bytes> [noreply]\r\n
cas <key> <flags> <exptime> <bytes> <cas unique> [noreply]\r\n

- <command name> is "set", "add", "replace", "append" or "prepend"

  "set" means "store this data".

  "add" means "store this data, but only if the server *doesn't* already
  hold data for this key".

  "replace" means "store this data, but only if the server *does*
  already hold data for this key".

  "append" means "add this data to an existing key after existing data".

  "prepend" means "add this data to an existing key before existing data".

  The append and prepend commands do not accept flags or exptime.
  They update existing data portions, and ignore new flag and exptime
  settings.

  "cas" is a check and set operation which means "store this data but
  only if no one else has updated since I last fetched it."

- <key> is the key under which the client asks to store the data

- <flags> is an arbitrary 16-bit unsigned integer (written out in
  decimal) that the server stores along with the data and sends back
  when the item is retrieved. Clients may use this as a bit field to
  store data-specific information; this field is opaque to the server.
  Note that in memcached 1.2.1 and higher, flags may be 32-bits, instead
  of 16, but you might want to restrict yourself to 16 bits for
  compatibility with older versions.

- <exptime> is expiration time. If it's 0, the item never expires
  (although it may be deleted from the cache to make place for other
  items). If it's non-zero (either Unix time or offset in seconds from
  current time), it is guaranteed that clients will not be able to
  retrieve this item after the expiration time arrives (measured by
  server time). If a negative value is given the item is immediately
  expired.

- <bytes> is the number of bytes in the data block to follow, *not*
  including the delimiting \r\n. <bytes> may be zero (in which case
  it's followed by an empty data block).

- <cas unique> is a unique 64-bit value of an existing entry.
  Clients should use the value returned from the "gets" command
  when issuing "cas" updates.

- "noreply" optional parameter instructs the server to not send the
  reply.  NOTE: if the request line is malformed, the server can't
  parse "noreply" option reliably.  In this case it may send the error
  to the client, and not reading it on the client side will break
  things.  Client should construct only valid requests.

After this line, the client sends the data block:

<data block>\r\n

- <data block> is a chunk of arbitrary 8-bit data of length <bytes>
  from the previous line.

After sending the command line and the data block the client awaits
the reply, which may be:

- "STORED\r\n", to indicate success.

- "NOT_STORED\r\n" to indicate the data was not stored, but not
because of an error. This normally means that the
condition for an "add" or a "replace" command wasn't met.

- "EXISTS\r\n" to indicate that the item you are trying to store with
a "cas" command has been modified since you last fetched it.

- "NOT_FOUND\r\n" to indicate that the item you are trying to store
with a "cas" command did not exist.


Retrieval command:
------------------

The retrieval commands "get" and "gets" operate like this:

get <key>*\r\n
gets <key>*\r\n

- <key>* means one or more key strings separated by whitespace.

After this command, the client expects zero or more items, each of
which is received as a text line followed by a data block. After all
the items have been transmitted, the server sends the string

"END\r\n"

to indicate the end of response.

Each item sent by the server looks like this:

VALUE <key> <flags> <bytes> [<cas unique>]\r\n
<data block>\r\n

- <key> is the key for the item being sent

- <flags> is the flags value set by the storage command

- <bytes> is the length of the data block to follow, *not* including
  its delimiting \r\n

- <cas unique> is a unique 64-bit integer that uniquely identifies
  this specific item.

- <data block> is the data for this item.

If some of the keys appearing in a retrieval request are not sent back
by the server in the item list this means that the server does not
hold items with such keys (because they were never stored, or stored
but deleted to make space for more items, or expired, or explicitly
deleted by a client).


Deletion
--------

The command "delete" allows for explicit deletion of items:

delete <key> [noreply]\r\n

- <key> is the key of the item the client wishes the server to delete

- "noreply" optional parameter instructs the server to not send the
  reply.  See the note in Storage commands regarding malformed
  requests.

The response line to this command can be one of:

- "DELETED\r\n" to indicate success

- "NOT_FOUND\r\n" to indicate that the item with this key was not
  found.

See the "flush_all" command below for immediate invalidation
of all existing items.


Increment/Decrement
-------------------

Commands "incr" and "decr" are used to change data for some item
in-place, incrementing or decrementing it. The data for the item is
treated as decimal representation of a 64-bit unsigned integer.  If
the current data value does not conform to such a representation, the
incr/decr commands return an error (memcached <= 1.2.6 treated the
bogus value as if it were 0, leading to confusion). Also, the item
must already exist for incr/decr to work; these commands won't pretend
that a non-existent key exists with value 0; instead, they will fail.

The client sends the command line:

incr <key> <value> [noreply]\r\n

or

decr <key> <value> [noreply]\r\n

- <key> is the key of the item the client wishes to change

- <value> is the amount by which the client wants to increase/decrease
the item. It is a decimal representation of a 64-bit unsigned integer.

- "noreply" optional parameter instructs the server to not send the
  reply.  See the note in Storage commands regarding malformed
  requests.

The response will be one of:

- "NOT_FOUND\r\n" to indicate the item with this value was not found

- <value>\r\n , where <value> is the new value of the item's data,
  after the increment/decrement operation was carried out.

Note that underflow in the "decr" command is caught: if a client tries
to decrease the value below 0, the new value will be 0.  Overflow in
the "incr" command will wrap around the 64 bit mark.

Note also that decrementing a number such that it loses length isn't
guaranteed to decrement its returned length.  The number MAY be
space-padded at the end, but this is purely an implementation
optimization, so you also shouldn't rely on that.

Touch
-----

The "touch" command is used to update the expiration time of an existing item
without fetching it.

touch <key> <exptime> [noreply]\r\n

- <key> is the key of the item the client wishes the server to touch

- <exptime> is expiration time. Works the same as with the update commands
  (set/add/etc). This replaces the existing expiration time. If an existing
  item were to expire in 10 seconds, but then was touched with an
  expiration time of "20", the item would then expire in 20 seconds.

- "noreply" optional parameter instructs the server to not send the
  reply.  See the note in Storage commands regarding malformed
  requests.

The response line to this command can be one of:

- "TOUCHED\r\n" to indicate success

- "NOT_FOUND\r\n" to indicate that the item with this key was not
  found.

Get And Touch
-------------

The "gat" and "gats" commands are used to fetch items and update the
expiration time of an existing items.

gat <exptime> <key>*\r\n
gats <exptime> <key>*\r\n

- <exptime> is expiration time.

- <key>* means one or more key strings separated by whitespace.

After this command, the client expects zero or more items, each of
which is received as a text line followed by a data block. After all
the items have been transmitted, the server sends the string

"END\r\n"

to indicate the end of response.

Each item sent by the server looks like this:

VALUE <key> <flags> <bytes> [<cas unique>]\r\n
<data block>\r\n

- <key> is the key for the item being sent

- <flags> is the flags value set by the storage command

- <bytes> is the length of the data block to follow, *not* including
  its delimiting \r\n

- <cas unique> is a unique 64-bit integer that uniquely identifies
  this specific item.

- <data block> is the data for this item.

Meta Debug
----------

The meta debug command is a human readable dump of all available internal
metadata of an item, minus the value.

me <key> <flag>\r\n

- <key> means one key string.
- if <flag> is 'b', then <key> is a base64 encoded binary value. the response
  key will also be base64 encoded.

The response looks like:

ME <key> <k>=<v>*\r\n

A miss looks like:

EN\r\n

Each of the keys and values are the internal data for the item.

exp   = expiration time
la    = time in seconds since last access
cas   = CAS ID
fetch = whether an item has been fetched before
cls   = slab class id
size  = total size in bytes

Others may be added.

Meta Get
--------

The meta get command is the generic command for retrieving key data from
memcached. Based on the flags supplied, it can replace all of the commands:
"get", "gets", "gat", "gats", "touch", as well as adding new options.

mg <key> <flags>*\r\n

- <key> means one key string. Unlike "get" metaget can only take a single key.

- <flags> are a set of single character codes ended with a space or newline.
  flags may have token strings after the initial character.

After this command, the client expects an item to be returned, received as a
text line followed by an optional data block.

If a response line appearing in a retrieval request is not sent back
by the server this means that the server does not
have the item (because it was never stored, or stored
but deleted to make space for more items, or expired, or explicitly
deleted by a client).

An item sent by the server looks like:

VA <size> <flags>*\r\n
<data block>\r\n

- <size> is the size of <data block> in bytes, minus the \r\n

- <flags>* are flags returned by the server, based on the command flags.
  They are added in order specified by the flags sent.

- <data block> is the data for this item. Note that the data block is
  optional, requiring the 'v' flag to be supplied.

If the request did not ask for a value in the response (v) flag, the server
response looks like:

HD <flags>*\r\n

If the request resulted in a miss, the response looks like:

EN\r\n

Unless the (q) flag was supplied, which suppresses the status code for a miss.

The flags used by the 'mg' command are:

- b: interpret key as base64 encoded binary value
- c: return item cas token
- f: return client flags token
- h: return whether item has been hit before as a 0 or 1
- k: return key as a token
- l: return time since item was last accessed in seconds
- O(token): opaque value, consumes a token and copies back with response
- q: use noreply semantics for return codes.
- s: return item size token
- t: return item TTL remaining in seconds (-1 for unlimited)
- u: don't bump the item in the LRU
- v: return item value in <data block>

These flags can modify the item:
- N(token): vivify on miss, takes TTL as a argument
- R(token): if token is less than remaining TTL win for recache
- T(token): update remaining TTL

These extra flags can be added to the response:
- W: client has "won" the recache flag
- X: item is stale
- Z: item has already sent a winning flag

The flags are now repeated with detailed information where useful:

- b: interpret key as base64 encoded binary value

This flag instructs memcached to run a base64 decoder on <key> before looking
it up. This allows storing and fetching of binary packed keys, so long as they
are sent to memcached in base64 encoding.

If 'b' flag is sent in the response, and a key is returned via 'k', this
signals to the client that the key is base64 encoded binary.

- h: return whether item has been hit before as a 0 or 1
- l: return time since item was last accessed in seconds

The above two flags return the value of "hit before?" and "last access time"
before the command was processed. Otherwise this would always show a 1 for
hit or always show an access time of "0" unless combined with the "u" flag.

- O(token): opaque value, consumes a token and copies back with response

The O(opaque) token is used by this and other commands to allow easier
pipelining of requests while saving bytes on the wire for responses. For
example: if pipelining three get commands together, you may not know which
response belongs to which without also retrieving the key. If the key is very
long this can generate a lot of traffic, especially if the data block is very
small. Instead, you can supply an "O" flag for each mg with tokens of "1" "2"
and "3", to match up responses to the request.

Opaque tokens may be up to 32 bytes in length, and are a string similar to
keys.

- q: use noreply semantics for return codes.

Noreply is a method of reducing the amount of data sent back by memcached to
the client for normal responses. In the case of metaget, if an item is not
available the "VA" line is normally not sent, and the response is terminated by
"EN\r\n".

With noreply enabled, the "EN\r\n" marker is suppressed. This allows you to
pipeline several mg's together and read all of the responses without the
"EN\r\n" lines in the middle.

Errors are always returned.

- u: don't bump the item in the LRU

It is possible to access an item without causing it to be "bumped" to the head
of the LRU. This also avoids marking an item as being hit or updating its last
access time.

- v: return item value in <data block>

The data block for a metaget response is optional, requiring this flag to be
passed in. The response code also changes from "HD" to "VA <size>"

These flags can modify the item:
- N(token): vivify on miss, takes TTL as a argument

Used to help with so called "dog piling" problems with recaching of popular
items. If supplied, and metaget does not find the item in cache, it will
create a stub item with the key and TTL as supplied. If such an item is
created a 'W' flag is added to the response to indicate to a client that they
have "won" the right to recache an item.

The automatically created item has 0 bytes of data.

Further requests will see a 'Z' flag to indicate that another client has
already received the win flag.

Can be combined with CAS flags to gate the update further.

- R(token): if token is less than remaining TTL win for recache

Similar to and can be combined with 'N'. If the remaining TTL of an item is
below the supplied token, return a 'W' flag to indicate the client has "won"
the right to recache an item. This allows refreshing an item before it leads to
a miss.

- T(token): update remaining TTL

Similar to "touch" and "gat" commands, updates the remaining TTL of an item if
hit.

These extra flags can be added to the response:
- W: client has "won" the recache flag

When combined with N or R flags, a client may be informed they have "won"
ownership of a cache item. This allows a single client to be atomically
notified that it should cache or update an item. Further clients requesting
the item can use the existing data block (if valid or stale), retry, wait, or
take some other action while the item is missing.

This is used when the act of recaching an item can cause undue load on another
system (CPU, database accesses, time, and so on).

- X: item is stale

Items can be marked as stale by the metadelete command. This indicates to the
client that an object needs to be updated, and that it should make a decision
o if potentially stale data is safe to use.

This is used when you want to convince clients to recache an item, but it's
safe to use pre-existing data while the recache happens.

- Z: item has already sent a winning flag

When combined with the X flag, or the client N or R flags, this extra response
flag indicates to a client that a different client is responsible for
recaching this item. If there is data supplied it may use it, or the client
may decide to retry later or take some other action.

Meta Set
--------

The meta set command a generic command for storing data to memcached. Based
on the flags supplied, it can replace all storage commands (see token M) as
well as adds new options.

ms <key> <datalen> <flags>*\r\n

- <key> means one key string.

- <datalen> is the length of the payload data.

- <flags> are a set of single character codes ended with a space or newline.
  flags may have strings after the initial character.

After this line, the client sends the data block:

<data block>\r\n

- <data block> is a chunk of arbitrary 8-bit data of length supplied by an 'S'
  flag and token from the request line. If no 'S' flag is supplied the data
  is assumed to be 0 length.

After sending the command line and the data block the client awaits
the reply, which is of the format:

<CD> <flags>*\r\n

Where CD is one of:

- "HD" (STORED), to indicate success.

- "NS" (NOT_STORED), to indicate the data was not stored, but not
because of an error.

- "EX" (EXISTS), to indicate that the item you are trying to store with
CAS semantics has been modified since you last fetched it.

- "NF" (NOT_FOUND), to indicate that the item you are trying to store
with CAS semantics did not exist.

The flags used by the 'ms' command are:

- b: interpret key as base64 encoded binary value (see metaget)
- c: return CAS value if successfully stored.
- C(token): compare CAS value when storing item
- F(token): set client flags to token (32 bit unsigned numeric)
- I: invalidate. set-to-invalid if supplied CAS is older than item's CAS
- k: return key as a token
- O(token): opaque value, consumes a token and copies back with response
- q: use noreply semantics for return codes
- s: return the size of the stored item on success (ie; new size on append)
- T(token): Time-To-Live for item, see "Expiration" above.
- M(token): mode switch to change behavior to add, replace, append, prepend
- N(token): if in append mode, autovivify on miss with supplied TTL

The flags are now repeated with detailed information where useful:

- c: returns the CAS value on successful storage. Will return 0 on error, but
  clients must not depend on the return value being zero. In future versions
this may return the current CAS value for "EX" return code conditions.

- C(token): compare CAS value when storing item

Similar to the basic "cas" command, only store item if the supplied token
matches the current CAS value of the item. When combined with the 'I' flag, a
CAS value that is _lower_ than the current value may be accepted, but the item
will be marked as "stale", returning the X flag with mget requests.

- F(token): set client flags to token (32 bit unsigned numeric)

Sets flags to 0 if not supplied.

- I: invalid. set-to-invalid if CAS is older than it should be.

Functional when combined with 'C' flag above.

- O(token): opaque value, consumes a token and copies back with response

See description under 'Meta Get'

- q: use noreply semantics for return codes

Noreply is a method of reducing the amount of data sent back by memcached to
the client for normal responses. In the case of metaset, a response that
would start with "HD" will not be sent. Any other code, such as "EX"
(EXISTS) will still be returned.

Errors are always returned.

- M(token): mode switch. Takes a single character for the mode.

E: "add" command. LRU bump and return NS if item exists. Else
add.
A: "append" command. If item exists, append the new value to its data.
P: "prepend" command. If item exists, prepend the new value to its data.
R: "replace" command. Set only if item already exists.
S: "set" command. The default mode, added for completeness.

The "cas" command is supplanted by specifying the cas value with the 'C' flag.
Append and Prepend modes will also respect a supplied cas value.

- N(token): if in append mode, autovivify on miss with supplied TTL

Append and Prepend modes normally ignore the T argument, as they cannot create
a new item on a miss. If N is supplied, and append reaches a miss, it will
create a new item seeded with the data from the append command. It uses the
TTL from N instead of T to be consistent with the usage of N in other
commands.

Meta Delete
-----------

The meta delete command allows for explicit deletion of items, as well as
marking items as "stale" to allow serving items as stale during revalidation.

md <key> <flags>*\r\n

- <key> means one key string.

- <flags> are a set of single character codes ended with a space or newline.
  flags may have strings after the initial character.

The response is in the format:

<CD> <flags> <tokens>*\r\n

Where CD is one of:

- "HD" (DELETED), to indicate success

- "NF" (NOT_FOUND), to indicate that the item with this key was not found.

- "EX" (EXISTS), to indicate that the supplied CAS token does not match the
  stored item.

The flags used by the 'md' command are:

- b: interpret key as base64 encoded binary value (see metaget)
- C(token): compare CAS value
- I: invalidate. mark as stale, bumps CAS.
- k: return key
- O(token): opaque to copy back.
- q: noreply
- T(token): updates TTL, only when paired with the 'I' flag

The flags are now repeated with detailed information where useful:

- C(token): compare CAS value

Can be used to only delete or mark-stale if a supplied CAS value matches.

- I: invalidate. mark as stale, bumps CAS.

Instead of removing an item, this will give the item a new CAS value and mark
it as stale. This means when it is later fetched by metaget, the client will
be supplied an 'X' flag to show the data is stale and needs to be recached.

- O(token): opaque to copy back.

See description under 'Meta Get'

- q: noreply

See description under 'Meta Set'. In the case of meta delete, this will hide
response lines with the code "DE". It will still return any other responses.

- T(token): updates TTL, only when paired with the 'I' flag

When marking an item as stale with 'I', the 'T' flag can be used to update the
TTL as well; limiting the amount of time an item will live while stale and
waiting to be recached.

Meta Arithmetic
---------------

The meta arithmetic command allows for basic operations against numerical
values. This replaces the "incr" and "decr" commands. Values are unsigned
64bit integers. Decrementing will reach 0 rather than underflow. Incrementing
can overflow.

ma <key> <flags>*\r\n

- <key> means one key string.

- <flags> are a set of single character codes ended with a space or newline.
  flags may have strings after the initial character.

The response is in the format:

<CD> <flags> <tokens>*\r\n

Where CD is one of:

- "HD" to indicate success

- "NF" (NOT_FOUND), to indicate that the item with this key was not found.

- "NS" (NOT_STORED), to indicate that the item was not created as requested
  after a miss.

- "EX" (EXISTS), to indicate that the supplied CAS token does not match the
  stored item.

If the 'v' flag is supplied, the response is formatted as:

VA <size> <flags>*\r\n
<number>\r\n

The flags used by the 'ma' command are:

- b: interpret key as base64 encoded binary value (see metaget)
- C(token): compare CAS value (see mset)
- N(token): auto create item on miss with supplied TTL
- J(token): initial value to use if auto created after miss (default 0)
- D(token): delta to apply (decimal unsigned 64-bit number, default 1)
- T(token): update TTL on success
- M(token): mode switch to change between incr and decr modes.
- O(token): opaque value, consumes a token and copies back with response
- q: use noreply semantics for return codes (see details under mset)
- t: return current TTL
- c: return current CAS value if successful.
- v: return new value
- k: return key as a token

The flags are now repeated with detailed information where useful:

- C(token): compare CAS value

Can be used to only incr/decr if a supplied CAS value matches. A new CAS value
is generated after a delta is applied. Add the 'c' flag to get the new CAS
value after success.

- N(token): auto create item on miss with supplied TTL

Similar to mget, on a miss automatically create the item. A value can be
seeded using the J flag.

- J(token): initial value

An unsigned 64-bit integer which will be seeded as the value on a miss. Must be
combined with an N flag.

- D(token): delta to apply

An unsigned integer to either add or subtract from the currently stored
number.

- T(token): update TTL

On success, sets the remaining TTL to the supplied value.

-M(token): mode switch. Takes a single character for the mode.

I: Increment mode (default)
+: Alias for increment
D: Decrement mode
-: Alias for decrement

Meta No-Op
----------

The meta no-op command exists solely to return a static response code. It
takes no flags, no arguments.

"mn\r\n"

This returns the static response:

"MN\r\n"

This command is useful when used with the 'q' flag and pipelining commands.
For example, with 'mg' the response lines are blank on miss when the 'q' flag
is supplied. If pipelining several 'mg's together with noreply semantics, an
"mn\r\n" command can be tagged to the end of the chain, which will return an
"MN\r\n", signalling to a client that all previous commands have been
processed.

Slabs Reassign
--------------

NOTE: This command is subject to change as of this writing.

The slabs reassign command is used to redistribute memory once a running
instance has hit its limit. It might be desirable to have memory laid out
differently than was automatically assigned after the server started.

slabs reassign <source class> <dest class>\r\n

- <source class> is an id number for the slab class to steal a page from

A source class id of -1 means "pick from any valid class"

- <dest class> is an id number for the slab class to move a page to

The response line could be one of:

- "OK" to indicate the page has been scheduled to move

- "BUSY [message]" to indicate a page is already being processed, try again
  later.

- "BADCLASS [message]" a bad class id was specified

- "NOSPARE [message]" source class has no spare pages

- "NOTFULL [message]" dest class must be full to move new pages to it

- "UNSAFE [message]" source class cannot move a page right now

- "SAME [message]" must specify different source/dest ids.

Slabs Automove
--------------

NOTE: This command is subject to change as of this writing.

The slabs automove command enables a background thread which decides on its
own when to move memory between slab classes. Its implementation and options
will likely be in flux for several versions. See the wiki/mailing list for
more details.

The automover can be enabled or disabled at runtime with this command.

slabs automove <0|1>

- 0|1|2 is the indicator on whether to enable the slabs automover or not.

The response should always be "OK\r\n"

- <0> means to set the thread on standby

- <1> means to return pages to a global pool when there are more than 2 pages
  worth of free chunks in a slab class. Pages are then re-assigned back into
  other classes as-needed.

- <2> is a highly aggressive mode which causes pages to be moved every time
  there is an eviction. It is not recommended to run for very long in this
  mode unless your access patterns are very well understood.

LRU Tuning
----------

Memcached supports multiple LRU algorithms, with a few tunables. Effort is
made to have sane defaults however you are able to tune while the daemon is
running.

The traditional model is "flat" mode, which is a single LRU chain per slab
class. The newer (with `-o modern` or `-o lru_maintainer`) is segmented into
HOT, WARM, COLD. There is also a TEMP LRU. See doc/new_lru.txt for details.

lru <tune|mode|temp_ttl> <option list>

- "tune" takes numeric arguments "percent hot", "percent warm",
  "max hot factor", "max warm age factor". IE: "lru tune 10 25 0.1 2.0".
  This would cap HOT_LRU at 10% of the cache, or tail is idle longer than
  10% of COLD_LRU. WARM_LRU is up to 25% of cache, or tail is idle longer
  than 2x COLD_LRU.

- "mode" <flat|segmented>: "flat" is traditional mode. "segmented" uses
  HOT|WARM|COLD split. "segmented" mode requires `-o lru_maintainer` at start
  time. If switching from segmented to flat mode, the background thread will
  pull items from HOT|WARM into COLD queue.

- "temp_ttl" <ttl>: If TTL is less than zero, disable usage of TEMP_LRU. If
  zero or above, items set with a TTL lower than this will go into TEMP_LRU
  and be unevictable until they naturally expire or are otherwise deleted or
  replaced.

The response line could be one of:

- "OK" to indicate a successful update of the settings.

- "ERROR [message]" to indicate a failure or improper arguments.

LRU_Crawler
-----------

NOTE: This command (and related commands) are subject to change as of this
writing.

The LRU Crawler is an optional background thread which will walk from the tail
toward the head of requested slab classes, actively freeing memory for expired
items. This is useful if you have a mix of items with both long and short
TTL's, but aren't accessed very often. This system is not required for normal
usage, and can add small amounts of latency and increase CPU usage.

lru_crawler <enable|disable>

- Enable or disable the LRU Crawler background thread.

The response line could be one of:

- "OK" to indicate the crawler has been started or stopped.

- "ERROR [message]" something went wrong while enabling or disabling.

lru_crawler sleep <microseconds>

- The number of microseconds to sleep in between each item checked for
  expiration. Smaller numbers will obviously impact the system more.
  A value of "0" disables the sleep, "1000000" (one second) is the max.

The response line could be one of:

- "OK"

- "CLIENT_ERROR [message]" indicating a format or bounds issue.

lru_crawler tocrawl <32u>

- The maximum number of items to inspect in a slab class per run request. This
  allows you to avoid scanning all of very large slabs when it is unlikely to
  find items to expire.

The response line could be one of:

- "OK"

- "CLIENT_ERROR [message]" indicating a format or bound issue.

lru_crawler crawl <classid,classid,classid|all>

- Takes a single, or a list of, numeric classids (ie: 1,3,10). This instructs
  the crawler to start at the tail of each of these classids and run to the
  head. The crawler cannot be stopped or restarted until it completes the
  previous request.

  The special keyword "all" instructs it to crawl all slabs with items in
  them.

The response line could be one of:

- "OK" to indicate successful launch.

- "BUSY [message]" to indicate the crawler is already processing a request.

- "BADCLASS [message]" to indicate an invalid class was specified.

lru_crawler metadump <classid,classid,classid|all|hash>

- Similar in function to the above "lru_crawler crawl" command, this function
  outputs one line for every valid item found in the matching slab classes.
  Similar to "cachedump", but does not lock the cache and can return all
  items, not just 1MB worth.

  if "hash" is specified instead of a classid or "all", the crawler will dump
  items by directly walking the hash table instead of the LRU's. This makes it
  more likely all items will be visited once as LRU reordering and locking can
  cause frequently accessed items to be missed.

  Lines are in "key=value key2=value2" format, with value being URI encoded
  (ie: %20 for a space).

  The exact keys available are subject to change, but will include at least:

  "key", "exp" (expiration time), "la", (last access time), "cas",
  "fetch" (if item has been fetched before).

The response line could be one of:

- "OK" to indicate successful launch.

- "BUSY [message]" to indicate the crawler is already processing a request.

- "BADCLASS [message]" to indicate an invalid class was specified.

lru_crawler mgdump <classid,classid,classid|all|hash>

- Similar in function to the above "lru_crawler crawl" command, this function
  outputs one line for every valid item found in the matching slab classes.

  If "hash" is specified instead of a classid or "all", the crawler will dump
  items by directly walking the hash table instead of the LRU's. This makes it
  more likely all items will be visited once as LRU reordering and locking can
  cause frequently accessed items to be missed.

  Lines are in a basic metaget format, like: "mg key\r\n". If a key is in
  binary format: "mg base64encodedkey b\r\n"
  A user may then take each line, append any flags they want, and run those
  commands against the server to fetch exactly what they want to know.

The response line could be one of:

- "OK" to indicate successful launch.

- "BUSY [message]" to indicate the crawler is already processing a request.

- "BADCLASS [message]" to indicate an invalid class was specified.



Watchers
--------

Watchers are a way to connect to memcached and inspect what's going on
internally. This is an evolving feature so new endpoints should show up over
time.

watch <fetchers|mutations|evictions|connevents|deletions>

- Turn connection into a watcher. Options can be stacked and are
  space-separated. Logs will be sent to the watcher until it disconnects.

The response line could be one of:

- "OK" to indicate the watcher is ready to send logs.

- "ERROR [message]" something went wrong while enabling.

The response format is in "key=value key2=value2" format, for easy parsing.
Lines are prepending with "ts=" for a timestamp and "gid=" for a global ID
number of the log line. Given how logs are collected internally they may be
printed out of order. If this is important the GID may be used to put log
lines back in order.

The value of keys (and potentially other things) are "URI encoded". Since most
keys used conform to standard ASCII, this should have no effect. For keys with
less standard or binary characters, "%NN"'s are inserted to represent the
byte, ie: "n%2Cfoo" for "n,foo".

The arguments are:

- "fetchers": Currently emits logs every time an item is fetched internally.
  This means a "set" command would also emit an item_get log, as it checks for
  an item before replacing it. Multigets should also emit multiple lines.

- "mutations": Currently emits logs when an item is stored in most cases.
  Shows errors for most cases when items cannot be stored.

- "evictions": Shows some information about items as they are evicted from the
  cache. Useful in seeing if items being evicted were actually used, and which
  keys are getting removed.

- "connevents": Emits logs when connections are opened and closed, i.e. when
  clients connect or disconnect. For TCP transports, logs indicate the remote
  address IP and port. Connection close events additionally supply a reason for
  closing the connection.

- "proxyreqs": Emits detailed timing logs about requests/responses being
  returned to a client while in proxy mode. The conditions which logs are
  written here may be influenced by configuration.

- "proxyevents": Emits internal proxy errors and system events, such as
  configuration reloads.

- "proxyuser": Emits log entries created from lua configuration files.

- "deletions": Emits logs when an item is successfully deleted from the
  cache using `delete` or `md` commands. delete misses wouldn't be logged

Statistics
----------

The command "stats" is used to query the server about statistics it
maintains and other internal data. It has two forms. Without
arguments:

stats\r\n

it causes the server to output general-purpose statistics and
settings, documented below.  In the other form it has some arguments:

stats <args>\r\n

Depending on <args>, various internal data is sent by the server. The
kinds of arguments and the data sent are not documented in this version
of the protocol, and are subject to change for the convenience of
memcache developers.


General-purpose statistics
--------------------------

Upon receiving the "stats" command without arguments, the server sends
a number of lines which look like this:

STAT <name> <value>\r\n

The server terminates this list with the line

END\r\n

In each line of statistics, <name> is the name of this statistic, and
<value> is the data.  The following is the list of all names sent in
response to the "stats" command, together with the type of the value
sent for this name, and the meaning of the value.

In the type column below, "32u" means a 32-bit unsigned integer, "64u"
means a 64-bit unsigned integer. '32u.32u' means two 32-bit unsigned
integers separated by a colon (treat this as a floating point number).

|-----------------------+---------+-------------------------------------------|
| Name                  | Type    | Meaning                                   |
|-----------------------+---------+-------------------------------------------|
| pid                   | 32u     | Process id of this server process         |
| uptime                | 32u     | Number of secs since the server started   |
| time                  | 32u     | current UNIX time according to the server |
| version               | string  | Version string of this server             |
| pointer_size          | 32      | Default size of pointers on the host OS   |
|                       |         | (generally 32 or 64)                      |
| rusage_user           | 32u.32u | Accumulated user time for this process    |
|                       |         | (seconds:microseconds)                    |
| rusage_system         | 32u.32u | Accumulated system time for this process  |
|                       |         | (seconds:microseconds)                    |
| curr_items            | 64u     | Current number of items stored            |
| total_items           | 64u     | Total number of items stored since        |
|                       |         | the server started                        |
| bytes                 | 64u     | Current number of bytes used              |
|                       |         | to store items                            |
| max_connections       | 32u     | Max number of simultaneous connections    |
| curr_connections      | 32u     | Number of open connections                |
| total_connections     | 32u     | Total number of connections opened since  |
|                       |         | the server started running                |
| rejected_connections  | 64u     | Conns rejected in maxconns_fast mode      |
| connection_structures | 32u     | Number of connection structures allocated |
|                       |         | by the server                             |
| response_obj_oom      | 64u     | Connections closed by lack of memory      |
| response_obj_count    | 64u     | Total response objects in use             |
| response_obj_bytes    | 64u     | Total bytes used for resp. objects. is a  |
|                       |         | subset of bytes from read_buf_bytes.      |
| read_buf_count        | 64u     | Total read/resp buffers allocated         |
| read_buf_bytes        | 64u     | Total read/resp buffer bytes allocated    |
| read_buf_bytes_free   | 64u     | Total read/resp buffer bytes cached       |
| read_buf_oom          | 64u     | Connections closed by lack of memory      |
| reserved_fds          | 32u     | Number of misc fds used internally        |
| proxy_conn_requests   | 64u     | Number of requests received by the proxy  |
| proxy_conn_errors     | 64u     | Number of internal errors from proxy      |
| proxy_conn_oom        | 64u     | Number of out of memory errors while      |
|                       |         | serving proxy requests                    |
| proxy_req_active      | 64u     | Number of in-flight proxy requests        |
| proxy_req_await       | 64u     | Number of in-flight proxy async requests  |
| cmd_get               | 64u     | Cumulative number of retrieval reqs       |
| cmd_set               | 64u     | Cumulative number of storage reqs         |
| cmd_flush             | 64u     | Cumulative number of flush reqs           |
| cmd_touch             | 64u     | Cumulative number of touch reqs           |
| get_hits              | 64u     | Number of keys that have been requested   |
|                       |         | and found present                         |
| get_misses            | 64u     | Number of items that have been requested  |
|                       |         | and not found                             |
| get_expired           | 64u     | Number of items that have been requested  |
|                       |         | but had already expired.                  |
| get_flushed           | 64u     | Number of items that have been requested  |
|                       |         | but have been flushed via flush_all       |
| delete_misses         | 64u     | Number of deletions reqs for missing keys |
| delete_hits           | 64u     | Number of deletion reqs resulting in      |
|                       |         | an item being removed.                    |
| incr_misses           | 64u     | Number of incr reqs against missing keys. |
| incr_hits             | 64u     | Number of successful incr reqs.           |
| decr_misses           | 64u     | Number of decr reqs against missing keys. |
| decr_hits             | 64u     | Number of successful decr reqs.           |
| cas_misses            | 64u     | Number of CAS reqs against missing keys.  |
| cas_hits              | 64u     | Number of successful CAS reqs.            |
| cas_badval            | 64u     | Number of CAS reqs for which a key was    |
|                       |         | found, but the CAS value did not match.   |
| touch_hits            | 64u     | Number of keys that have been touched     |
|                       |         | with a new expiration time                |
| touch_misses          | 64u     | Number of items that have been touched    |
|                       |         | and not found                             |
| store_too_large       | 64u     | Number of rejected storage requests       |
|                       |         | caused by attempting to write a value     |
|                       |         | larger than the -I limit                  |
| store_no_memory       | 64u     | Number of rejected storage requests       |
|                       |         | caused by exhaustion of the -m memory     |
|                       |         | limit (relevant when -M is used)          |
| auth_cmds             | 64u     | Number of authentication commands         |
|                       |         | handled, success or failure.              |
| auth_errors           | 64u     | Number of failed authentications.         |
| idle_kicks            | 64u     | Number of connections closed due to       |
|                       |         | reaching their idle timeout.              |
| evictions             | 64u     | Number of valid items removed from cache  |
|                       |         | to free memory for new items              |
| reclaimed             | 64u     | Number of times an entry was stored using |
|                       |         | memory from an expired entry              |
| bytes_read            | 64u     | Total number of bytes read by this server |
|                       |         | from network                              |
| bytes_written         | 64u     | Total number of bytes sent by this server |
|                       |         | to network                                |
| limit_maxbytes        | size_t  | Number of bytes this server is allowed to |
|                       |         | use for storage.                          |
| accepting_conns       | bool    | Whether or not server is accepting conns  |
| listen_disabled_num   | 64u     | Number of times server has stopped        |
|                       |         | accepting new connections (maxconns).     |
| time_in_listen_disabled_us                                                  |
|                       | 64u     | Number of microseconds in maxconns.       |
| threads               | 32u     | Number of worker threads requested.       |
|                       |         | (see doc/threads.txt)                     |
| conn_yields           | 64u     | Number of times any connection yielded to |
|                       |         | another due to hitting the -R limit.      |
| hash_power_level      | 32u     | Current size multiplier for hash table    |
| hash_bytes            | 64u     | Bytes currently used by hash tables       |
| hash_is_expanding     | bool    | Indicates if the hash table is being      |
|                       |         | grown to a new size                       |
| expired_unfetched     | 64u     | Items pulled from LRU that were never     |
|                       |         | touched by get/incr/append/etc before     |
|                       |         | expiring                                  |
| evicted_unfetched     | 64u     | Items evicted from LRU that were never    |
|                       |         | touched by get/incr/append/etc.           |
| evicted_active        | 64u     | Items evicted from LRU that had been hit  |
|                       |         | recently but did not jump to top of LRU   |
| slab_reassign_running | bool    | If a slab page is being moved             |
| slabs_moved           | 64u     | Total slab pages moved                    |
| crawler_reclaimed     | 64u     | Total items freed by LRU Crawler          |
| crawler_items_checked | 64u     | Total items examined by LRU Crawler       |
| lrutail_reflocked     | 64u     | Times LRU tail was found with active ref. |
|                       |         | Items can be evicted to avoid OOM errors. |
| moves_to_cold         | 64u     | Items moved from HOT/WARM to COLD LRU's   |
| moves_to_warm         | 64u     | Items moved from COLD to WARM LRU         |
| moves_within_lru      | 64u     | Items reshuffled within HOT or WARM LRU's |
| direct_reclaims       | 64u     | Times worker threads had to directly      |
|                       |         | reclaim or evict items.                   |
| lru_crawler_starts    | 64u     | Times an LRU crawler was started          |
| lru_maintainer_juggles                                                      |
|                       | 64u     | Number of times the LRU bg thread woke up |
| slab_global_page_pool | 32u     | Slab pages returned to global pool for    |
|                       |         | reassignment to other slab classes.       |
| slab_reassign_rescues | 64u     | Items rescued from eviction in page move  |
| slab_reassign_evictions_nomem                                               |
|                       | 64u     | Valid items evicted during a page move    |
|                       |         | (due to no free memory in slab)           |
| slab_reassign_chunk_rescues                                                 |
|                       | 64u     | Individual sections of an item rescued    |
|                       |         | during a page move.                       |
| slab_reassign_inline_reclaim                                                |
|                       | 64u     | Internal stat counter for when the page   |
|                       |         | mover clears memory from the chunk        |
|                       |         | freelist when it wasn't expecting to.     |
| slab_reassign_busy_items                                                    |
|                       | 64u     | Items busy during page move, requiring a  |
|                       |         | retry before page can be moved.           |
| slab_reassign_busy_deletes                                                  |
|                       | 64u     | Items busy during page move, requiring    |
|                       |         | deletion before page can be moved.        |
| log_worker_dropped    | 64u     | Logs a worker never wrote due to full buf |
| log_worker_written    | 64u     | Logs written by a worker, to be picked up |
| log_watcher_skipped   | 64u     | Logs not sent to slow watchers.           |
| log_watcher_sent      | 64u     | Logs written to watchers.                 |
| log_watchers          | 64u     | Number of currently active watchers.      |
| unexpected_napi_ids   | 64u     | Number of times an unexpected napi id is  |
|                       |         | is received. See doc/napi_ids.txt         |
| round_robin_fallback  | 64u     | Number of times napi id of 0 is received  |
|                       |         | resulting in fallback to round robin      |
|                       |         | thread selection. See doc/napi_ids.txt    |
|-----------------------+---------+-------------------------------------------|

Settings statistics
-------------------
CAVEAT: This section describes statistics which are subject to change in the
future.

The "stats" command with the argument of "settings" returns details of
the settings of the running memcached.  This is primarily made up of
the results of processing commandline options.

Note that these are not guaranteed to return in any specific order and
this list may not be exhaustive.  Otherwise, this returns like any
other stats command.

|-------------------+----------+----------------------------------------------|
| Name              | Type     | Meaning                                      |
|-------------------+----------+----------------------------------------------|
| maxbytes          | size_t   | Maximum number of bytes allowed in the cache |
| maxconns          | 32       | Maximum number of clients allowed.           |
| tcpport           | 32       | TCP listen port.                             |
| udpport           | 32       | UDP listen port.                             |
| inter             | string   | Listen interface.                            |
| verbosity         | 32       | 0 = none, 1 = some, 2 = lots                 |
| oldest            | 32u      | Age of the oldest honored object.            |
| evictions         | on/off   | When off, LRU evictions are disabled.        |
| domain_socket     | string   | Path to the domain socket (if any).          |
| umask             | 32 (oct) | umask for the creation of the domain socket. |
| shutdown_command  | yes/no   | If shutdown admin command is enabled.        |
| growth_factor     | float    | Chunk size growth factor.                    |
| chunk_size        | 32       | Minimum space allocated for key+value+flags. |
| num_threads       | 32       | Number of threads (including dispatch).      |
| stat_key_prefix   | char     | Stats prefix separator character.            |
| detail_enabled    | bool     | If yes, stats detail is enabled.             |
| reqs_per_event    | 32       | Max num IO ops processed within an event.    |
| cas_enabled       | bool     | When no, CAS is not enabled for this server. |
| tcp_backlog       | 32       | TCP listen backlog.                          |
| auth_enabled_sasl | yes/no   | SASL auth requested and enabled.             |
| item_size_max     | size_t   | maximum item size                            |
| maxconns_fast     | bool     | If fast disconnects are enabled              |
| hashpower_init    | 32       | Starting size multiplier for hash table      |
| slab_reassign     | bool     | Whether slab page reassignment is allowed    |
| slab_automove     | bool     | Whether slab page automover is enabled       |
| slab_automove_ratio                                                         |
|                   | float    | Ratio limit between young/old slab classes   |
| slab_automove_window                                                        |
|                   | 32u      | Internal algo tunable for automove           |
| slab_chunk_max    | 32       | Max slab class size (avoid unless necessary) |
| hash_algorithm    | char     | Hash table algorithm in use                  |
| lru_crawler       | bool     | Whether the LRU crawler is enabled           |
| lru_crawler_sleep | 32       | Microseconds to sleep between LRU crawls     |
| lru_crawler_tocrawl                                                         |
|                   | 32u      | Max items to crawl per slab per run          |
| lru_maintainer_thread                                                       |
|                   | bool     | Split LRU mode and background threads        |
| hot_lru_pct       | 32       | Pct of slab memory reserved for HOT LRU      |
| warm_lru_pct      | 32       | Pct of slab memory reserved for WARM LRU     |
| hot_max_factor    | float    | Set idle age of HOT LRU to COLD age * this   |
| warm_max_factor   | float    | Set idle age of WARM LRU to COLD age * this  |
| temp_lru          | bool     | If yes, items < temporary_ttl use TEMP_LRU   |
| temporary_ttl     | 32u      | Items with TTL < this are marked  temporary  |
| idle_time         | 0        | Drop connections that are idle this many     |
|                   |          | seconds (0 disables)                         |
| watcher_logbuf_size                                                         |
|                   | 32u      | Size of internal (not socket) write buffer   |
|                   |          | per active watcher connected.                |
| worker_logbuf_size| 32u      | Size of internal per-worker-thread buffer    |
|                   |          | which the background thread reads from.      |
| read_obj_mem_limit| 32u      | Megabyte limit for conn. read/resp buffers.  |
| track_sizes       | bool     | If yes, a "stats sizes" histogram is being   |
|                   |          | dynamically tracked.                         |
| inline_ascii_response                                                       |
|                   | bool     | Does nothing as of 1.5.15                    |
| drop_privileges   | bool     | If yes, and available, drop unused syscalls  |
|                   |          | (see seccomp on Linux, pledge on OpenBSD)    |
| proxy_enabled     | bool     | If proxy has been configured at start        |
| proxy_uring_enabled                                                         |
                    | bool     | If proxy is configured to use IO_URING.      |
                    |          | NOTE: uring may be used if kernel too old    |
| memory_file       | char     | Warm restart memory file path, if enabled    |
|-------------------+----------+----------------------------------------------|


Item statistics
---------------
CAVEAT: This section describes statistics which are subject to change in the
future.

The "stats" command with the argument of "items" returns information about
item storage per slab class. The data is returned in the format:

STAT items:<slabclass>:<stat> <value>\r\n

The server terminates this list with the line

END\r\n

The slabclass aligns with class ids used by the "stats slabs" command. Where
"stats slabs" describes size and memory usage, "stats items" shows higher
level information.

The following item values are defined as of writing.

Name                   Meaning
------------------------------
number                 Number of items presently stored in this class. Expired
                       items are not automatically excluded.
number_hot             Number of items presently stored in the HOT LRU.
number_warm            Number of items presently stored in the WARM LRU.
number_cold            Number of items presently stored in the COLD LRU.
number_temp            Number of items presently stored in the TEMPORARY LRU.
age_hot                Age of the oldest item in HOT LRU.
age_warm               Age of the oldest item in WARM LRU.
age                    Age of the oldest item in the LRU.
mem_requested          Number of bytes requested to be stored in this LRU[*]
evicted                Number of times an item had to be evicted from the LRU
                       before it expired.
evicted_nonzero        Number of times an item which had an explicit expire
                       time set had to be evicted from the LRU before it
                       expired.
evicted_time           Seconds since the last access for the most recent item
                       evicted from this class. Use this to judge how
                       recently active your evicted data is.
outofmemory            Number of times the underlying slab class was unable to
                       store a new item. This means you are running with -M or
                       an eviction failed.
tailrepairs            Number of times we self-healed a slab with a refcount
                       leak. If this counter is increasing a lot, please
                       report your situation to the developers.
reclaimed              Number of times an entry was stored using memory from
                       an expired entry.
expired_unfetched      Number of expired items reclaimed from the LRU which
                       were never touched after being set.
evicted_unfetched      Number of valid items evicted from the LRU which were
                       never touched after being set.
evicted_active         Number of valid items evicted from the LRU which were
                       recently touched but were evicted before being moved to
                       the top of the LRU again.
crawler_reclaimed      Number of items freed by the LRU Crawler.
lrutail_reflocked      Number of items found to be refcount locked in the
                       LRU tail.
moves_to_cold          Number of items moved from HOT or WARM into COLD.
moves_to_warm          Number of items moved from COLD to WARM.
moves_within_lru       Number of times active items were bumped within
                       HOT or WARM.
direct_reclaims        Number of times worker threads had to directly pull LRU
                       tails to find memory for a new item.
hits_to_hot
hits_to_warm
hits_to_cold
hits_to_temp           Number of get_hits to each sub-LRU.

Note this will only display information about slabs which exist, so an empty
cache will return an empty set.

* Items are stored in a slab that is the same size or larger than the
  item.  mem_requested shows the size of all items within a
  slab. (total_chunks * chunk_size) - mem_requested shows memory
  wasted in a slab class.  If you see a lot of waste, consider tuning
  the slab factor.


Item size statistics
--------------------
CAVEAT: This section describes statistics which are subject to change in the
future.

The "stats" command with the argument of "sizes" returns information about the
general size and count of all items stored in the cache.
WARNING: In versions prior to 1.4.27 this command causes the cache server to
lock while it iterates the items. 1.4.27 and greater are safe.

The data is returned in the following format:

STAT <size> <count>\r\n

The server terminates this list with the line

END\r\n

'size' is an approximate size of the item, within 32 bytes.
'count' is the amount of items that exist within that 32-byte range.

This is essentially a display of all of your items if there was a slab class
for every 32 bytes. You can use this to determine if adjusting the slab growth
factor would save memory overhead. For example: generating more classes in the
lower range could allow items to fit more snugly into their slab classes, if
most of your items are less than 200 bytes in size.

In 1.4.27 and after, this feature must be manually enabled.

A "stats" command with the argument of "sizes_enable" will enable the
histogram at runtime. This has a small overhead to every store or delete
operation. If you don't want to incur this, leave it off.

A "stats" command with the argument of "sizes_disable" will disable the
histogram.

It can also be enabled at starttime with "-o track_sizes"

If disabled, "stats sizes" will return:

STAT sizes_status disabled\r\n

"stats sizes_enable" will return:

STAT sizes_status enabled\r\n

"stats sizes_disable" will return:

STAT sizes_status disabled\r\n

If an error happens, it will return:

STAT sizes_status error\r\n
STAT sizes_error [error_message]\r\n

CAVEAT: If CAS support is disabled, you cannot enable/disable this feature at
runtime.

Slab statistics
---------------
CAVEAT: This section describes statistics which are subject to change in the
future.

The "stats" command with the argument of "slabs" returns information about
each of the slabs created by memcached during runtime. This includes per-slab
information along with some totals. The data is returned in the format:

STAT <slabclass>:<stat> <value>\r\n
STAT <stat> <value>\r\n

The server terminates this list with the line

END\r\n

|-----------------+----------------------------------------------------------|
| Name            | Meaning                                                  |
|-----------------+----------------------------------------------------------|
| chunk_size      | The amount of space each chunk uses. One item will use   |
|                 | one chunk of the appropriate size.                       |
| chunks_per_page | How many chunks exist within one page. A page by         |
|                 | default is less than or equal to one megabyte in size.   |
|                 | Slabs are allocated by page, then broken into chunks.    |
| total_pages     | Total number of pages allocated to the slab class.       |
| total_chunks    | Total number of chunks allocated to the slab class.      |
| get_hits        | Total number of get requests serviced by this class.     |
| cmd_set         | Total number of set requests storing data in this class. |
| delete_hits     | Total number of successful deletes from this class.      |
| incr_hits       | Total number of incrs modifying this class.              |
| decr_hits       | Total number of decrs modifying this class.              |
| cas_hits        | Total number of CAS commands modifying this class.       |
| cas_badval      | Total number of CAS commands that failed to modify a     |
|                 | value due to a bad CAS id.                               |
| touch_hits      | Total number of touches serviced by this class.          |
| used_chunks     | How many chunks have been allocated to items.            |
| free_chunks     | Chunks not yet allocated to items, or freed via delete.  |
| free_chunks_end | Number of free chunks at the end of the last allocated   |
|                 | page.                                                    |
| active_slabs    | Total number of slab classes allocated.                  |
| total_malloced  | Total amount of memory allocated to slab pages.          |
|-----------------+----------------------------------------------------------|


Connection statistics
---------------------
The "stats" command with the argument of "conns" returns information
about currently active connections and about sockets that are listening
for new connections. The data is returned in the format:

STAT <file descriptor>:<stat> <value>\r\n

The server terminates this list with the line

END\r\n

The following "stat" keywords may be present:

|---------------------+------------------------------------------------------|
| Name                | Meaning                                              |
|---------------------+------------------------------------------------------|
| addr                | The address of the remote side. For listening        |
|                     | sockets this is the listen address. Note that some   |
|                     | socket types (such as UNIX-domain) don't have        |
|                     | meaningful remote addresses.                         |
| listen_addr         | The address of the server. This field is absent      |
|                     | for listening sockets.                               |
| state               | The current state of the connection. See below.      |
| secs_since_last_cmd | The number of seconds since the most recently        |
|                     | issued command on the connection. This measures      |
|                     | the time since the start of the command, so if       |
|                     | "state" indicates a command is currently executing,  |
|                     | this will be the number of seconds the current       |
|                     | command has been running.                            |
|---------------------+------------------------------------------------------|

The value of the "state" stat may be one of the following:

|----------------+-----------------------------------------------------------|
| Name           | Meaning                                                   |
|----------------+-----------------------------------------------------------|
| conn_closing   | Shutting down the connection.                             |
| conn_listening | Listening for new connections or a new UDP request.       |
| conn_mwrite    | Writing a complex response, e.g., to a "get" command.     |
| conn_new_cmd   | Connection is being prepared to accept a new command.     |
| conn_nread     | Reading extended data, typically for a command such as    |
|                | "set" or "put".                                           |
| conn_parse_cmd | The server has received a command and is in the middle    |
|                | of parsing it or executing it.                            |
| conn_read      | Reading newly-arrived command data.                       |
| conn_swallow   | Discarding excess input, e.g., after an error has         |
|                | occurred.                                                 |
| conn_waiting   | A partial command has been received and the server is     |
|                | waiting for the rest of it to arrive (note the difference |
|                | between this and conn_nread).                             |
| conn_write     | Writing a simple response (anything that doesn't involve  |
|                | sending back multiple lines of response data).            |
|----------------+-----------------------------------------------------------|

TLS statistics
--------------

TLS is a compile-time opt-in feature available in versions 1.5.13 and later.
When compiled with TLS support and TLS termination is enabled at runtime, the
following additional statistics are available via the "stats" command.

|--------------------------------+----------+--------------------------------|
| Name                           | Type     | Meaning                        |
|--------------------------------+----------+--------------------------------|
| ssl_handshake_errors           | 64u      | Number of times the server has |
|                                |          | encountered an OpenSSL error   |
|                                |          | during handshake (SSL_accept). |
| ssl_min_version                | char     | Minimum supported TLS version  |
|                                |          | for client handshakes.         |
| ssl_new_sessions               | 64u      | When SSL session caching is    |
|                                |          | enabled, the number of newly   |
|                                |          | created server-side sessions.  |
|                                |          | Available only when compiled   |
|                                |          | with OpenSSL 1.1.1 or newer.   |
| time_since_server_cert_refresh | 32u      | Number of seconds that have    |
|                                |          | elapsed since the last time    |
|                                |          | certs were reloaded from disk. |
|--------------------------------+----------+--------------------------------|


Other commands
--------------

"flush_all" is a command with an optional numeric argument. It always
succeeds, and the server sends "OK\r\n" in response (unless "noreply"
is given as the last parameter). Its effect is to invalidate all
existing items immediately (by default) or after the expiration
specified.  After invalidation none of the items will be returned in
response to a retrieval command (unless it's stored again under the
same key *after* flush_all has invalidated the items). flush_all
doesn't actually free all the memory taken up by existing items; that
will happen gradually as new items are stored. The most precise
definition of what flush_all does is the following: it causes all
items whose update time is earlier than the time at which flush_all
was set to be executed to be ignored for retrieval purposes.

The intent of flush_all with a delay, was that in a setting where you
have a pool of memcached servers, and you need to flush all content,
you have the option of not resetting all memcached servers at the
same time (which could e.g. cause a spike in database load with all
clients suddenly needing to recreate content that would otherwise
have been found in the memcached daemon).

The delay option allows you to have them reset in e.g. 10 second
intervals (by passing 0 to the first, 10 to the second, 20 to the
third, etc. etc.).

"cache_memlimit" is a command with a numeric argument. This allows runtime
adjustments of the cache memory limit. It returns "OK\r\n" or an error (unless
"noreply" is given as the last parameter). If the new memory limit is higher
than the old one, the server may start requesting more memory from the OS. If
the limit is lower, and slabs_reassign+automove are enabled, free memory may
be released back to the OS asynchronously.

The argument is in megabytes, not bytes. Input gets multiplied out into
megabytes internally.

"shutdown" is a command with an optional argument used to stop memcached with
a kill signal. By default, "shutdown" alone raises SIGINT, though "graceful"
may be specified as the single argument to instead trigger a graceful shutdown
with SIGUSR1. The shutdown command is disabled by default, and can be enabled
with the -A/--enable-shutdown flag.

"version" is a command with no arguments:

version\r\n

In response, the server sends

"VERSION <version>\r\n", where <version> is the version string for the
server.

"verbosity" is a command with a numeric argument. It always succeeds,
and the server sends "OK\r\n" in response (unless "noreply" is given
as the last parameter). Its effect is to set the verbosity level of
the logging output.

"quit" is a command with no arguments:

quit\r\n

Upon receiving this command, the server closes the
connection. However, the client may also simply close the connection
when it no longer needs it, without issuing this command.

Security restrictions
---------------------

In the debug build the following commands are available for testing the
security restrictions:

"misbehave" is a command with no arguments:

misbehave\r\n

This command causes the worker thread to attempt a) opening a new socket, and
b) executing a shell command. If either one is successful, an error is
returned. Otherwise memcached returns OK.
The check is available only in Linux builds with seccomp enabled.


UDP protocol
------------

For very large installations where the number of clients is high enough
that the number of TCP connections causes scaling difficulties, there is
also a UDP-based interface. The UDP interface does not provide guaranteed
delivery, so should only be used for operations that aren't required to
succeed; typically it is used for "get" requests where a missing or
incomplete response can simply be treated as a cache miss.

Each UDP datagram contains a simple frame header, followed by data in the
same format as the TCP protocol described above. In the current
implementation, requests must be contained in a single UDP datagram, but
responses may span several datagrams. (The only common requests that would
span multiple datagrams are huge multi-key "get" requests and "set"
requests, both of which are more suitable to TCP transport for reliability
reasons anyway.)

The frame header is 8 bytes long, as follows (all values are 16-bit integers
in network byte order, high byte first):

0-1 Request ID
2-3 Sequence number
4-5 Total number of datagrams in this message
6-7 Reserved for future use; must be 0

The request ID is supplied by the client. Typically it will be a
monotonically increasing value starting from a random seed, but the client
is free to use whatever request IDs it likes. The server's response will
contain the same ID as the incoming request. The client uses the request ID
to differentiate between responses to outstanding requests if there are
several pending from the same server; any datagrams with an unknown request
ID are probably delayed responses to an earlier request and should be
discarded.

The sequence number ranges from 0 to n-1, where n is the total number of
datagrams in the message. The client should concatenate the payloads of the
datagrams for a given response in sequence number order; the resulting byte
stream will contain a complete response in the same format as the TCP
protocol (including terminating \r\n sequences).