Top Banner
CACHING MEMCACHED vs. REDIS vs. FILESYSTEM Brown Bag Session Rafi Adnan Faisal Islam
29
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Caching

CACHINGMEMCACHED vs. REDIS vs. FILESYSTEM

Brown Bag Session

Rafi AdnanFaisal Islam

Page 2: Caching

What is caching in web application?

Web application caching is the process of storing dynamically generated data for reuse and leaving data closer to the end user.

Page 3: Caching

How Caching Works

Page 4: Caching

Traditional Data Query (Without Cache)

Query

Get Rows From Database

Return Rows to Application

Page 5: Caching

Cached Data QueryQuery

Data In

Cache

Get Rows From Database

Return Row to Application

Insert Rows Into

Cache

Cache StorageDatabase

Yes

No

Page 6: Caching

Why we use?➔ Better performance

◆ System loads faster/better responsiveness

➔ Better scalability

◆ Limit bottlenecks in a system

➔ Better robustness

◆ Can support more load

Page 7: Caching

When to use?

Profile your application to find operations that consume significant CPU time and/or memory

try - “New Relic”

Don’t be premature

Page 8: Caching

CachingTerminology

[ Cache Hit ]when requested data is contained in the cache

[ Cache Miss ]when requested not in the cached, has to be recomputed or fetched from original storage

[ Cache Key ]unique identifier for a data item in the cache

[ Expiration ]item expires at a specific date (absolute), specifies how long after an item was last accessed that is expires (sliding)

[ Backing store ]persist cached data on disk

[ Cache Scavenging ]deleting items from the cache when memory is scarce

[ Local Cache ]caching data on clients rather than on servers

[ Distributed Cache ]extension of the traditional concept of cache that may span multiple servers

Page 9: Caching

Advantages❖ Speed up application

❖ Less Resources Used

❖ Reuse content

Disadvantages

❖ Stale Data

❖ Overhead

❖ Complexity

Page 10: Caching

Type Of Caching❑ Client Caching - browser caches URLs for future uses - Mozilla Firefox, Google Chrome

❑ Proxy Caching- proxy server caches most requested URLs

- Varnish ( reverse proxy ) - CDN ( forward proxy )

❑ Server-side Caching- server side cache reduces load on server

- File System Cache - In-Memory Cache (MemCached, Redis)

Page 11: Caching

File Cache

A file of data on a local hard drive. When downloaded data are temporarily stored on the

user's local disk or on a local network disk, it speeds up retrieval the next time the user wants that same data (Web page, graphic, etc.) from the Internet or

other remote source.

Page 12: Caching

In-Memory means We are Bound By RAM

Page 13: Caching

MemCached

Memcached is an in-memory key-value store for small chunks of arbitrary data

(strings, objects) from results of database calls, API calls, or page

rendering.

Page 14: Caching

Redis

Redis is an open source, advanced key-value store. It is often referred to as a "data structure server" since keys can contain strings, hashes, lists, sets and

sorted sets.

Page 15: Caching

How to use?

[ File System Caching ]

➔ It works without any additional server. Most of the CMS by default use file cache without any configurations.

[ In-Memory Caching ]

➔ Need to install and configure cache server

➔ Need client library to access cache

➔ Most of the popular framework has very good built-in or third-party library.

Page 16: Caching

In-Memory Cache ( Server - Client )

Installing memcached server (ubuntu):

sudo apt-get install memcached

Installing memcached client(ubuntu):

PHP :

sudo apt-get install php5-memcached

Ruby on Rails :

Popular gem called Dalli (https://github.com/mperham/dalli)

Installing redis server (ubuntu):

sudo apt-get install redis-server

Redis client 3rd-party packages:

PHP : Predis , phpredis

Ruby on Rails : redis-rb, em-hiredis, redic

Python : redis-py, txredisapi, brukva

(http://redis.io/clients)

Page 17: Caching

MemCached

➔ Dead Simple & Battle Tested

➔ Fast

➔ Non-Blocking get()/set()

➔ Multi-Threaded

➔ Consistent Hashing

Page 18: Caching

Code Example - Memcached$memCached = new Memcached();

//connect with memcached server

$memCached->addServer('127.0.0.1', '11211');

const INT_EXPIRATION_TIME_IN_SECONDS = 2;

//Set cache

$memCached->set('key_1', 'serialize data',

INT_EXPIRATION_TIME_IN_SECONDS);

//get cache

//if call unique_key after 2 seconds it will return

false

$uniqueKeyValue = $memCached->get('key_1');

var_export($uniqueKeyValue);

Output :

'serialize data'

Client

Port

Server Addr

Page 19: Caching

Code Example - Memcached$memCached = new Memcached();//connect with memcached server$memCached->addServer('127.0.0.1', '11211');//consider our data set below$employeeId = 1000;$employeeData = array( 'name' => 'Rafi Adnan', 'designation' => 'Software Engineer', 'joining_date' => '2014-09-15');$memCached->set($employeeId, json_encode($employeeData));// Returns employee details as json$employeeDetail = $memCached->get($employeeId);var_export($employeeDetail);

Output :

{"name":"Rafi Adnan","designation":"Software Engineer","joining_date":"2014-09-15"}

Page 20: Caching

What if I don't want all the data?

➔ What if I just want the name?

➔ 64 bytes for the object vs 16 bytes for just the name?

➔ 4X network traffic

➔ More work for the application

Page 21: Caching

Redis: Data Types

➔ Strings ( just like Memcached )

➔ Lists

➔ Sets

➔ Sorted Sets

➔ Hashes

Page 22: Caching

Redis : Lists

➔ Stored in sorted order

➔ Can push/pop

➔ Fast head/tail access

➔ Index access

Page 23: Caching

Code Example - Redis : Lists

$redisClient = new Predis\Client();

$redisClient->lpush('employees', 'Faisal');$redisClient->lpush('employees', 'Rafi');

$arrEmployeeList = $redisClient->lrange('employees', 0, -1);var_export($arrEmployeeList);

$redisClient->rpush('employees', 'Akhtar');

$arrEmployeeList = $redisClient->lrange('employees', 0, -1);var_export($arrEmployeeList);

array ( 0 => 'Rafi', 1 => 'Faisal',)

array ( 0 => 'Rafi', 1 => 'Faisal', 2 => 'Akhtar',)

Page 24: Caching

Redis : Sets

➔ Unordered collections of strings

➔ Unique ( no repeated members )

➔ diff, intersect, merge

Page 25: Caching

Code Example - Redis : Sets$redisClient = new Predis\Client();

$redisClient->sadd('employees', 'Rafi Adnan');$redisClient->sadd('employees', 'Saeed Ahmed');$redisClient->sadd('employees', 'Faisal Islam');

$redisClient->sadd('formerEmployees', 'Saeed Ahmed');

$currentEmployees = $redisClient->sdiff('employees', 'formerEmployees');

var_export($currentEmployees); array ( 0 => 'Rafi Adnan', 1 => 'Faisal Islam',)

Page 26: Caching

Code Example - Redis : Hashes

$redisClient = new Predis\Client();

$redisClient->hset('employees', 'teamCount', 10);$redisClient->hset('employees', 'rubyTeam', 9);$redisClient->hset('employees', 'phpTeam', 1);

$teamCount = $redisClient->hget('employees', 'teamCount');var_export($teamCount);

$teamStatus = $redisClient->hgetall('employees');var_export($teamStatus);

array ( 'teamCount' => '10', 'rubyTeam' => '9', 'phpTeam' => '1',)

‘10’ - string

Page 27: Caching

Redis: The Bad

➔ Single-Threaded

➔ Limited client support for consistent hashing

➔ Significant overhead for persistence

➔ Not widely deployed

Page 28: Caching

Memcached vs. RedisMemcached Redis

(multi) get ✔ ✔

(multi) set ✔ ✔

increment/decrement ✔ ✔

delete ✔ ✔

expiration ✔ ✔

range queries ✔

data types ✔

persistence - ✔

multi-threaded ✔

replication - ✔

Page 29: Caching

Die;

Questions, comments...