• This repository has been archived on 02/Nov/2021
  • Stars
    star
    925
  • Rank 47,379 (Top 1.0 %)
  • Language
    C
  • License
    BSD 3-Clause "New...
  • Created almost 12 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Twemcache is the Twitter Memcached

Twemcache: Twitter Memcached

status: retired Build Status

Twemcache is no longer actively maintained. See twitter/pelikan for our latest caching work.

Twemcache (pronounced "tw-em-cache") is the Twitter Memcached. Twemcache is based on a fork of Memcached v.1.4.4 that has been heavily modified to make to suitable for the large scale production environment at Twitter.

Build

To build twemcache from distribution tarball:

$ ./configure
$ make
$ sudo make install

To build twemcache from distribution tarball with a non-standard path to libevent install:

$ ./configure --with-libevent=<path>
$ make
$ sudo make install

To build twemcache from distribution tarball with a statically linked libevent:

$ ./configure --enable-static=libevent
$ make
$ sudo make install

To build twemcache from distribution tarball in debug mode with assertion panics enabled:

$ CFLAGS="-ggdb3 -O0" ./configure --enable-debug=full
$ make
$ sudo make install

To build twemcache from source with debug logs enabled and assertions disabled:

$ git clone [email protected]:twitter/twemcache.git
$ cd twemcache
$ autoreconf -fvi
$ ./configure --enable-debug=log
$ make V=1
$ src/twemcache -h

Help

Usage: twemcache [-?hVCELdkrDS] [-o output file] [-v verbosity level]
           [-A stats aggr interval]
           [-t threads] [-P pid file] [-u user]
           [-x command logging entry] [-X command logging file]
           [-R max requests] [-c max conns] [-b backlog] [-p port] [-U udp port]
           [-l interface] [-s unix path] [-a access mask] [-M eviction strategy]
           [-f factor] [-m max memory] [-n min item chunk size] [-I slab size]
           [-z slab profile]

Options:
  -h, --help                  : this help
  -V, --version               : show version and exit
  -E, --prealloc              : preallocate memory for all slabs
  -L, --use-large-pages       : use large pages if available
  -k, --lock-pages            : lock all pages and preallocate slab memory
  -d, --daemonize             : run as a daemon
  -r, --maximize-core-limit   : maximize core file limit
  -C, --disable-cas           : disable use of cas
  -D, --describe-stats        : print stats description and exit
  -S, --show-sizes            : print slab and item struct sizes and exit
  -o, --output=S              : set the logging file (default: stderr)
  -v, --verbosity=N           : set the logging level (default: 5, min: 0, max: 11)
  -A, --stats-aggr-interval=N : set the stats aggregation interval in usec (default: 100000 usec)
  -t, --threads=N             : set number of threads to use (default: 4)
  -P, --pidfile=S             : set the pid file (default: off)
  -u, --user=S                : set user identity when run as root (default: off)
  -x, --klog-entry=N          : set the command logging entry number per thread (default: 512)
  -X, --klog-file=S           : set the command logging file (default: off)
  -R, --max-requests=N        : set the maximum number of requests per event (default: 20)
  -c, --max-conns=N           : set the maximum simultaneous connections (default: 1024)
  -b, --backlog=N             : set the backlog queue limit (default 1024)
  -p, --port=N                : set the tcp port to listen on (default: 11211)
  -U, --udp-port=N            : set the udp port to listen on (default: 11211)
  -l, --interface=S           : set the interface to listen on (default: all)
  -s, --unix-path=S           : set the unix socket path to listen on (default: off)
  -a, --access-mask=O         : set the access mask for unix socket in octal (default: 0700)
  -M, --eviction-strategy=N   : set the eviction strategy on OOM (default: 2, random)
  -f, --factor=D              : set the growth factor of slab item sizes (default: 1.25)
  -m, --max-memory=N          : set the maximum memory to use for all items in MB (default: 64 MB)
  -n, --min-item-chunk-size=N : set the minimum item chunk size in bytes (default: 72 bytes)
  -I, --slab-size=N           : set slab size in bytes (default: 1048576 bytes)
  -z, --slab-profile=S        : set the profile of slab item chunk sizes (default: off)

Features

  • Supports the complete memcached ASCII protocol.
  • Supports tcp, udp and unix domain sockets.
  • Observability through lock-less stats collection and klogger.
  • Pluggable eviction strategies.
  • Easy debuggability through assertions and logging.

Slabs and Items

Memory in twemcache is organized into fixed sized slabs whose size is configured using the -I or --slab-size=N command-line argument. Every slab is carved into a collection of contiguous, equal size items. All slabs that are carved into items of a given size belong to a given slabclass. The number of slabclasses and the size of items they serve can be configured either from a geometric sequence with the inital item size set using -n or --min-item-chunk-size=N argument and growth ratio set using -f or --factor=D argument, or from a profile string set using -z or --slab-profile=S argument.

Eviction

Eviction is triggered when a cache reaches full memory capacity. This happens when all cached items are unexpired and there is no space available to store newer items. Twemcache supports the following eviction strategies, configured using the -M or --eviction-strategy=N command-line argument:

  • No eviction (0) - don't evict, respond with server error reply.
  • Item LRU eviction (1) - evict only existing items in the same slab class, least recently updated first; essentially a per-slabclass LRU eviction.
  • Random eviction (2) - evict all items from a randomly chosen slab.
  • Slab LRA eviction (4) - choose the least recently accessed slab, and evict all items from it to reuse the slab.
  • Slab LRC eviction (8) - choose the least recently created slab, and evict all items from it to reuse the slab. Eviction ignores freeq & lruq to make sure the eviction follows the timestamp closely. Recommended if cache is updated on the write path.

Eviction strategies can be stacked, in the order of higher to lower bit. For example, -M 5 means that if slab LRA eviciton fails, Twemcache will try item LRU eviction.

Observability

Stats

Stats are the primary form of observability in twemcache. Stats collection in twemcache is lock-less in a sense that each worker thread only updates its thread-local metrics, and a background aggregator thread collects metrics from all threads periodically, holding only one thread-local lock at a time. Once aggregated, stats polling comes for free. There is a slight trade-off between how up-to-date stats are and how much burden stats collection puts on the system, which can be controlled by the aggregation interval -A or --stats-aggr-interval=N command-line argument. By default, the aggregation interval is set to 100 msec. You can set the aggregation interval at run time using config aggregate <num>\r\n command. Stats collection can be disabled at run time by passing a negative aggregation interval or at build time through the --disable-stats configure option.

Metrics exposed by twemcache are of three types - timestamp, counter and gauge and are collected both at the global level and per slab level. You can read about the description of all stats exposed by twemcache using the -D or --describe-stats command-line argument.

The following commands can be used to query stats from a running twemcache

  • stats\r\n
  • stats settings\r\n
  • stats slabs\r\n
  • stats sizes\r\n
  • stats cachedump <id> <limit>\r\n

Klogger (Command Logger)

Command logger allows users to capture the details of every incoming request. Each line of the command log gives precise information on the client, the time when a request was received, the command header including the command, key, flags and data length, a return code, and reply message length. Few example klog lines look as follows:

172.25.135.205:55438 - [09/Jul/2012:18:15:45 -0700] "set foo 0 0 3" 1 6
172.25.135.205:55438 - [09/Jul/2012:18:15:46 -0700] "get foo" 0 14
172.25.135.205:55438 - [09/Jul/2012:18:15:57 -0700] "incr num 1" 3 9
172.25.135.205:55438 - [09/Jul/2012:18:16:05 -0700] "set num 0 0 1" 1 6
172.25.135.205:55438 - [09/Jul/2012:18:16:09 -0700] "incr num 1" 0 1
172.25.135.205:55438 - [09/Jul/2012:18:16:13 -0700] "get num" 0 12

The command logger supports lockless read/write into ring buffers, whose size can be configured with -x or --klog-entry=N command-line argument. Each worker thread logs to a thread-local buffer as they process incoming queries, and a background thread asynchronously dumps buffer contents to a file configured with -X or --klog-file=S command-line argument.

Since this feature has the capability of generating hundreds of MBs of data per minute, the use must be planned carefully. An enabled klog moduled can be started or stopped by sending config klog run start\r\n and config klog run stop\r\n respectively. To control the speed of log generation, the command logger also supports sampling. Sample rate can be set over with config klog sampling <num>\r\n command, which samples one of num commands.

Logging

Logging in twemcache is only available when it is built with logging enabled (--enable-debug=[full|yes|log]). By default logs are written to stderr. Twemcache can also be configured to write logs to a specific file through the -o or --output=S command-line argument.

On a running twemcache, we can turn log levels up and down by sending it SIGTTIN and SIGTTOU signals respectively and reopen log files by sending it SIGHUP signal. Logging levels can be set to a specific value using the verbosity <num>\r\n command.

Issues and Support

Have a bug? Please create an issue here on GitHub!

https://github.com/twitter/twemcache/issues

Versioning

For transparency and insight into our release cycle, releases are be numbered with the semantic versioning format: <major>.<minor>.<patch> and constructed with the following guidelines:

  • Breaking backwards compatibility bumps the major
  • New additions without breaking backwards compatibility bumps the minor
  • Bug fixes and misc changes bump the patch

Other Work

  • twemproxy - a fast, light-weight proxy for memcached.
  • twemperf - a tool for measuring memcached server performance.
  • twctop.rb - a tool like top for monitoring a cluster of twemcache servers.

Contributors

License

Copyright 2003, Danga Interactive, Inc.

Copyright 2012 Twitter, Inc.

Licensed under the New BSD License, see the LICENSE file.

More Repositories

1

the-algorithm

Source code for Twitter's Recommendation Algorithm
Scala
60,968
star
2

twemoji

Emoji for everyone. https://twemoji.twitter.com/
HTML
16,575
star
3

typeahead.js

typeahead.js is a fast and fully-featured autocomplete library
JavaScript
16,526
star
4

twemproxy

A fast, light-weight proxy for memcached and redis
C
12,000
star
5

the-algorithm-ml

Source code for Twitter's Recommendation Algorithm
Python
9,844
star
6

finagle

A fault tolerant, protocol-agnostic RPC system
Scala
8,742
star
7

hogan.js

A compiler for the Mustache templating language
JavaScript
5,143
star
8

labella.js

Placing labels on a timeline without overlap.
JavaScript
3,869
star
9

scala_school

Lessons in the Fundamentals of Scala
HTML
3,700
star
10

AnomalyDetection

Anomaly Detection with R
R
3,529
star
11

scalding

A Scala API for Cascading
Scala
3,469
star
12

twitter-text

Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.
HTML
3,051
star
13

TwitterTextEditor

A standalone, flexible API that provides a full-featured rich text editor for iOS applications.
Swift
2,950
star
14

opensource-website

Twitter's open source website, identifying projects we've released, organizations we support, and the work we do to support open source.
SCSS
2,918
star
15

util

Wonderful reusable code from Twitter
Scala
2,679
star
16

algebird

Abstract Algebra for Scala
Scala
2,288
star
17

finatra

Fast, testable, Scala services built on TwitterServer and Finagle
Scala
2,271
star
18

effectivescala

Twitter's Effective Scala Guide
HTML
2,241
star
19

summingbird

Streaming MapReduce with Scalding and Storm
Scala
2,136
star
20

pelikan

Pelikan is Twitter's unified cache backend
C
1,921
star
21

ios-twitter-image-pipeline

Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients
C
1,851
star
22

twurl

OAuth-enabled curl for the Twitter API
Ruby
1,790
star
23

twitter-server

Twitter-Server defines a template from which services at Twitter are built
Scala
1,542
star
24

rezolus

Systems performance telemetry
Rust
1,541
star
25

activerecord-reputation-system

An Active Record Reputation System for Rails
Ruby
1,334
star
26

communitynotes

Documentation and source code powering Twitter's Community Notes
Python
1,319
star
27

compose-rules

Static checks to aid with a healthy adoption of Compose
Kotlin
1,311
star
28

fatcache

Memcache on SSD
C
1,301
star
29

rsc

Experimental Scala compiler focused on compilation speed
Scala
1,245
star
30

elephant-bird

Twitter's collection of LZO and Protocol Buffer-related Hadoop, Pig, Hive, and HBase code.
Java
1,137
star
31

cassovary

Cassovary is a simple big graph processing library for the JVM
Scala
1,039
star
32

Serial

Light-weight, fast framework for object serialization in Java, with Android support.
Java
988
star
33

hbc

A Java HTTP client for consuming Twitter's realtime Streaming API
Java
963
star
34

innovators-patent-agreement

Innovators Patent Agreement (IPA)
919
star
35

vireo

Vireo is a lightweight and versatile video processing library written in C++11
C++
919
star
36

twitter-korean-text

Korean tokenizer
Scala
834
star
37

scrooge

A Thrift parser/generator
Scala
785
star
38

BreakoutDetection

Breakout Detection via Robust E-Statistics
C++
753
star
39

GraphJet

GraphJet is a real-time graph processing library.
Java
696
star
40

twitter-cldr-rb

Ruby implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more.
Ruby
667
star
41

bijection

Reversible conversions between types
Scala
657
star
42

chill

Scala extensions for the Kryo serialization library
Scala
607
star
43

ios-twitter-network-layer

Twitter Network Layer is a scalable and feature rich network layer built on top of NSURLSession for Apple platforms
Objective-C
574
star
44

hadoop-lzo

Refactored version of code.google.com/hadoop-gpl-compression for hadoop 0.20
Shell
544
star
45

storehaus

Storehaus is a library that makes it easy to work with asynchronous key value stores
Scala
464
star
46

rpc-perf

A tool for benchmarking RPC services
Rust
458
star
47

d3kit

D3Kit is a set tools to speed D3 related project development
JavaScript
429
star
48

scoot

Scoot is a distributed task runner, supporting both a proprietary API and Bazel's Remote Execution.
Go
347
star
49

twitter-cldr-js

JavaScript implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more. Based on twitter-cldr-rb.
JavaScript
345
star
50

scala_school2

Scala School 2
Scala
340
star
51

rustcommon

Common Twitter Rust lib
Rust
339
star
52

wordpress

The official Twitter plugin for WordPress. Embed Twitter content and grow your audience on Twitter.
PHP
310
star
53

ios-twitter-logging-service

Twitter Logging Service is a robust and performant logging framework for iOS clients
Objective-C
299
star
54

nodes

A library to implement asynchronous dependency graphs for services in Java
Java
246
star
55

SentenTree

A novel text visualization technique
JavaScript
226
star
56

interactive

Twitter interactive visualization
HTML
213
star
57

joauth

A Java library for authenticating HTTP Requests using OAuth
Java
211
star
58

thrift_client

A Thrift client wrapper that encapsulates some common failover behavior
Ruby
196
star
59

hpack

Header Compression for HTTP/2
Java
192
star
60

zktraffic

ZooKeeper protocol analyzer and stats gathering daemon
Python
165
star
61

twemoji-parser

A simple library for identifying emoji entities within a string in order to render them as Twemoji.
Scala
162
star
62

cache-trace

A collection of Twitter's anonymized production cache traces.
Shell
162
star
63

sbf

Java
159
star
64

tormenta

Scala extensions for Storm
Scala
132
star
65

whiskey

HTTP library for Android (beta)
Java
131
star
66

hraven

hRaven collects run time data and statistics from MapReduce jobs in an easily queryable format
Java
127
star
67

netty-http2

HTTP/2 for Netty
Java
120
star
68

sqrl

A Safe, Stateful Rules Language for Event Streams
TypeScript
100
star
69

ccommon

Cache Commons
C
99
star
70

focus

Focus aligns Git worktree content based on outlines of a repository's Bazel build graph. Focused repos are sparse, shallow, and thin and unlock markedly better performance in large repos.
Rust
91
star
71

dict_minimize

Access scipy optimizers from your favorite deep learning framework.
Python
77
star
72

metrics

76
star
73

twitter.github.io

HTML
71
star
74

go-bindata

Go
68
star
75

diffusion-rl

Python
66
star
76

birdwatch

64
star
77

cloudhopper-commons

Cloudhopper Commons
Java
57
star
78

twitter-cldr-npm

TwitterCldr npm package
JavaScript
49
star
79

.github

Twitter GitHub Organization-wide files
48
star
80

bazel-multiversion

Bazel rules to resolve, fetch and manage 3rdparty JVM dependencies with support for multiple parallel versions of the same dependency. Powered by Coursier.
Scala
47
star
81

libwatchman

A C interface to watchman
C
44
star
82

sslconfig

Twitter's OpenSSL Configuration
42
star
83

ios-twitter-apache-thrift

A thrift encoding and decoding library for Swift
Swift
41
star
84

gatekeeper-service

GateKeeper is a service built to automate the manual steps involved in onboarding, offboarding, and lost asset scenarios.
Python
36
star
85

dodo

The Twitter OSS Project Builder
Shell
35
star
86

repo-scaffolding

Tools for creating repos based on open source standards and best practices
33
star
87

iago2

A load generator, built for engineers
Scala
24
star
88

caladrius

Performance modelling system for Distributed Stream Processing Systems (DSPS) such as Apache Heron and Apache Storm
Python
22
star
89

ossdecks

Repository for Twitter Open Source Decks
10
star
90

curation-style-guide

Document Repository for Twitter's Curation Style Guide
10
star
91

analytics-infra-governance

Description of the process for how to commit, review, and release code to the Scalding OSS family (Scalding, Summingbird, Algebird, Bijection, Storehaus, etc)
9
star
92

gpl-commitment

Twitter's GPL Cooperation Commitment
5
star
93

second-control-probability-distributions

4
star
94

google-tag-manager-event-tag

Smarty
3
star
95

google-tag-manager-base-tag

Smarty
2
star