SlideShare a Scribd company logo
APC & Memcache the High
    Performance Duo
    Dutch PHP Conference 2010


         Ilia Alshanetsky
           http://ilia.ws/


                                1
What is APC?

• Alternative PHP Cache
• Primarily designed to accelerate script
 performance via opcode caching

• Extends opcode caching to facilitate user-data
 caching

• Actively maintained & well supported


                                                   2
Opcode Caching
     Default Mode                                                            With APC
                                                                                     PHP Script
                  PHP Script




                                                   APC
                                                                                     Opcode Cache


                  Zend Compile




                                                     Zend Compile           No       Data Cached?




                  Zend Execute
                                                                                         Yes
                                                    Cache Opcode




Function/Method
                                 Require/Include
      Call                                                                           Zend Execute




                                                                   Function/Method
                                                                                                    Require/Include
                                                                         Call




                                                                                                                      3
APC User-Cache

• Allows you to apply the same caching logic to
 your data as applied to PHP scripts.




Slide Motto:
  Not everything has to be real-time!



                                                  4
APC in Practice
// store an array of values for 1 day, referenced by "identifier"
if (!apc_add("identifier", array(1,2,3), 86400)) {
    // already exists? let's update it instead
    if (!apc_store("identifier", array(1,2,3), 86400)) {
        // uh, oh, b0rkage
    }
}

$ok = null;
// fetch value associated with "identified" and
// put success state into $ok variable
$my_array = apc_fetch("identifier", $ok);
if ($ok) {
    // changed my mind, let's delete it
    apc_delete("identifier");
}



                                                                    5
Let’s be lazy

// create or update an array of values for 1 day
if (!apc_store("identifier", array(1,2,3), 86400)) {
  // uh, oh, b0rkage
  mail("gopal, brian, kalle", "you broke my code", "fix it!");
}




 If you don’t care whether your are adding or updating
 values you can just use apc_store() and keep your
 code simpler



                                                                 6
Don’t Delete
• Deleting from cache is expensive as it may need
 to re-structure internal hash tables.

    • Rely on auto-expiry functionality instead
    • Or an off-stream cron job to clean up stale
      cache entries

• In many cases it is simpler just to start from
 scratch.

      apc_clear_cache(“user”)

                                                    7
Installing APC
# Unix

sudo bash (open root shell)

pecl install apc (configure, compile & install APC)

# Windows

Copy the php_apc.dll file into your php’s ext/
directory

# Common

Enable APC from your php.ini file

                                                     8
Advantages of APC

• If you (or your ISP) uses opcode caching,
 chances are it is already there.

• Really efficient at storing simple types (scalars
 & arrays)

• Really simple to use, can’t get any easier…
• Fairly stable


                                                    9
APC Limitations


• PHP only, can’t talk to other “stuff ”
• Not distributed, local only
• Opcode + User cache == all eggs in one basket
• Could be volatile



                                                  10
Memcached

• Interface to Memcached - a distributed caching
 system

• Provides Object Oriented interface to caching
 system

• Offers a built-in session handler
• Can only be used for “user” caching
• Purpose built, so lots of nifty features

                                                   11
Memcache vs Memcached

• Memcached Advantages
  • Faster
    • Igbinary serializer
    • fastlz compression
  • Multi-Server Interface
  • Fail-over callback support

                                 12
Basics in Practice
$mc = new MemCached();

// connect to memcache on local machine, on default port
$mc->addServer('localhost', '11211');

// try to add an array with a retrieval key for 1 day
if (!$mc->add('key', array(1,2,3), 86400)) {
    // if already exists, let's replace it
    if ($mc->replace('key', array(1,2,3), 86400)) {
        die("Critical Error");
    }
}

// let's fetch our data
if (($data = $mc->get('key')) !== FALSE) {
    // let's delete it now
    $mc->delete('key'); // RIGHT NOW!
}


                                                           13
Data Retrieval Gotcha(s)
$mc = new MemCached();
$mc->addServer('localhost', '11211');


$mc->add('key', 0);


if (!($data = $mc->get('key'))) {
  die("Not Found?"); // not true
  // The value could be 0,array(),NULL,””
  // always compare Memcache::get() result to
  // FALSE constant in a type-sensitive way (!== FALSE)
}

// The “right” way!
if (($data = $mc->get('key')) !== FALSE) {
  die("Not Found");
}


                                                          14
Data Retrieval Gotcha(s)
$mc = new MemCached();
$mc->addServer('localhost', '11211');

$mc->add('key', FALSE);

if (($data = $mc->get('key')) !== FALSE) {
  die("Not Found?"); // not true
  // The value could be FALSE, you
  // need to check the response code
}

// The “right” way!
if (
       (($data = $mc->get('key')) !== FALSE)
       &&
       ($mc->getResultCode() != MemCached::RES_SUCCESS)
) {
  die("Not Found");
}

                                                          15
Interface Basics Continued...
$mc = new MemCached();
// on local machine we can connect via Unix Sockets for better speed
$mc->addServer('/var/run/memcached/11211.sock', 0);

// add/or replace, don't care just get it in there
// without expiration parameter, will remain in cache “forever”
$mc->set('key1', array(1,2,3));

$key_set = array('key1' => “foo”, 'key1' => array(1,2,3));

// store multiple keys at once for 1 hour
$mc->setMulti($key_set, 3600);

// get multiple keys at once
$data = $mc->getMulti(array_keys($key_set));
/*
array(                                 For multi-(get|set), all   ops
    'key1' => ‘foo’
    'key2' => array(1,2,3)                  must succeed for
)
*/
                                            successful return.
                                                                        16
Multi-Server Environment

$mc = new MemCached();

// add multiple servers to the list
// as many servers as you like can be added
$mc->addServers(
     array('localhost', 11211, 80), // high-priority 80%
     array('192.168.1.90', 11211, 20)// low-priority 20%
);

// You can also do it one at a time, but this is not recommended
$mc->addServer('localhost', 11211, 80);
$mc->addServer('192.168.1.90', 11211, 20);

// Get a list of servers in the pool
$mc->	
  getServerList();
// array(array(‘host’ => … , ‘port’ => … ‘weight’ => …))



                                                                   17
Data Segmentation
    • Memcached interface allows you to store
      certain types of data on specific servers
$mc = new MemCached();
$mc->addServers( … );

// Add data_key with a value of “value” for 10 mins to server
// identified by “server_key”
$mc->addByKey('server_key', 'data_key', 'value', 600);

// Fetch key from specific server
$mc->getByKey('server_key', 'data_key');

// Add/update key on specific server
$mc->setByKey('server_key', 'data_key', 'value', 600);

// Remove key from specific server
$mc->deleteByKey('server_key', 'data_key');

                                                                18
And there is more ...
• The specific-server interface also supports multi-(get|set)

$mc = new MemCached();
$mc->addServers( … );

$key_set = array('key1' => “foo”, 'key1' => array(1,2,3));

// store multiple keys at once for 1 hour
$mc->setMultiByKey('server_key', $key_set, 3600);

// get multiple keys at once
$data = $mc->getMultiByKey('server_key', array_keys($key_set));




                                                                  19
Delayed Data Retrieval

• One of the really neat features of Memcached
 extension is the ability to execute the “fetch”
 command, but defer the actual data retrieval
 until later.



• Particularly handy when retrieving many keys
 that won’t be needed until later.



                                                   20
Delayed Data Retrieval

$mc = new MemCached();
$mc->addServer('localhost', '11211');

$mc->getDelayed(array('key')); // parameter is an array of keys

/* some PHP code that does “stuff” */

// Fetch data one record at a time
while ($data = $mc->fetch()) { ... }

// Fetch all data in one go
$data = $mc->fetchAll();




                                                                  21
Atomic Counters
$mc = new MemCached();
$mc->addServer('localhost', 11211);

// initialize counter to 1
$mc->set('my_counter', 1);

// increase count by 1
$mc->increment('my_counter');

// increase count by 10
$mc->increment('my_counter', 10);

// decrement count by 1
$mc->decrement('my_counter');

// decrement count by 10
$mc->decrement('my_counter', 10);


                                      22
Counter Trick
$mc = new MemCached();
$mc->addServer('localhost', 11211);

// add key position if does not already exist
if (!$mc->add('key_pos', 1)) {
    // otherwise increment it
    $position = $mc->increment('key_pos');
} else {
    $position = 1;
}

// add real value at the new position
$mc->add('key_value_' . $position, array(1,2,3));



     • Simplifies cache invalidation
     • Reduces lock contention (or eliminates it)
                                                    23
Data Compression
• In many cases performance can be gained by
 compressing large blocks of data. Since in most cases
 network IO is more expensive then CPU speed + RAM.
     $mc = new MemCached();
     $mc->addServer('localhost', 11211);
     // enable compression
     $mc->setOption(Memcached::OPT_COMPRESSION, TRUE);

            Related INI settings (INI_ALL)
            Other possible value is zlib
            memcached.compression_type=fastlz

            minimum compression rate
            memcached.compression_factor=1.3

            minimum data size to compress
            memcached.compression_threshold=2000

                                                         24
PHP Serialization

If you are using memcached to store complex data type
(arrays & objects), they will need to be converted to
strings for the purposes of storage, via serialization.



Memcached can make use of igbinary serializer that
works faster (~30%) and produces more compact data set
(up-to 45% smaller) than native PHP serializer.

           http://github.com/phadej/igbinary

                                                          25
Enabling Igbinary
Install Memcached extension with
--enable-memcached-igbinary

$mc = new MemCached();
$mc->addServer('localhost', 11211);

// use Igbinary serializer
$mc->setOption(
   Memcached::OPT_SERIALIZER,
   Memcached::SERIALIZER_IGBINARY
);




                                      26
Utility Methods
                                Array
                                (
                                	
  	
  	
  	
  [server:port]	
  =>	
  Array
                                	
  	
  	
  	
  	
  	
  	
  	
  (
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [pid]	
  =>	
  4933
$mc = new MemCached();          	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [uptime]	
  =>	
  786123
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [threads]	
  =>	
  1
$mc->addServer('localhost', 11211);
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [time]	
  =>	
  1233868010
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [pointer_size]	
  =>	
  32
// memcached statistics gathering
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [rusage_user_seconds]	
  =>	
  0
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [rusage_user_microseconds]	
  =>	
  140000
$mc->getStats();                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [rusage_system_seconds]	
  =>	
  23
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [rusage_system_microseconds]	
  =>	
  210000
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [curr_items]	
  =>	
  145
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [total_items]	
  =>	
  2374
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [limit_maxbytes]	
  =>	
  67108864
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [curr_connections]	
  =>	
  2
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [total_connections]	
  =>	
  151
// clear all cache entries      	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [a]	
  =>	
  3
$mc->flush();                   	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [bytes]	
  =>	
  20345
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [cmd_get]	
  =>	
  213343
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [cmd_set]	
  =>	
  2381
// clear all cache entries      	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [get_hits]	
  =>	
  204223
// in 10 minutes                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [get_misses]	
  =>	
  9120
$mc->flush(600);                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [evictions]	
  =>	
  0
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [bytes_read]	
  =>	
  9092476
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [bytes_written]	
  =>	
  15420512
                                	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [version]	
  =>	
  1.2.6
                                	
  	
  	
  	
  	
  	
  	
  	
  )
                                )
                                                                                                                               27
Installing Memcached


Download memcached from http://
www.memcached.org and compile it.

Download libmemcached from http://tangent.org/552/
libmemcached.html and compile it.

pecl install memcached (configure, make, make install)

Enable Memcached from your php.ini file



                                                        28
Memcached Session Handler

# Session settings

session.save_handler # set to “memcached

session.save_path # set to memcache host server:port

memcached.sess_prefix # Defaults to memc.sess.key.

# Locking Controls

# Whether to enable session lock, on by default
memcached.sess_locking

# Maximum number of microseconds to wait on a lock
memcached.sess_lock_wait



                                                       29
Advantages of Memcache

• Allows other languages to talk to it
• One instance can be shared by multiple servers
• Failover & redundancy
• Nifty Features
• Very stable


                                                   30
It is not perfect because?


• Slower then APC, especially for array storage
• Requires external daemon
• You can forget about it on
 shared hosting




                                                  31
That’s all folks



       Any Questions?

  Slides at: http://ilia.ws
Comments: http://joind.in/1554
                                 32
APC Configuration

apc.enable # enable APC
apc.enable_cli # enable for CLI sapi
apc.max_file_size # max PHP file to be cached
apc.stat # turn off ONLY if your files never change
apc.file_update_protection # good idea if you edit files on
live environment

apc.filters # posix (ereg) expressions to filter out files
from being cached

apc.mmap_file_mask # /tmp/apc.XXXXXX (use mmap IO, USE IT!)
apc.shm_segments # if not using mmap IO, otherwise 1
apc.shm_size # how much memory to use




                                                              33
Make PHBs Happy




                 ✴   Pretty graphics require GD extension


• For raw data you can use the apc_cache_info()
 and apc_sma_info() functions.
                                                            34

More Related Content

PDF
Apc Memcached Confoo 2011
PDF
Facebook的缓存系统
PDF
4069180 Caching Performance Lessons From Facebook
PDF
Cloud, Cache, and Configs
PDF
Introduction to PHP 5.3
PDF
Tips
PDF
Php on Windows
PPTX
Php on the Web and Desktop
Apc Memcached Confoo 2011
Facebook的缓存系统
4069180 Caching Performance Lessons From Facebook
Cloud, Cache, and Configs
Introduction to PHP 5.3
Tips
Php on Windows
Php on the Web and Desktop

What's hot (18)

PDF
Understanding PHP objects
PDF
Ansible : what's ansible & use case by REX
PDF
APC & Memcache the High Performance Duo
PDF
The symfony platform: Create your very own framework (PHP Quebec 2008)
PDF
Managing themes and server environments with extensible configuration arrays
PDF
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
PDF
When symfony met promises
PPTX
Php on the desktop and php gtk2
PPTX
Always On, Multi-Site Design Considerations
PDF
Supercharging WordPress Development in 2018
ODP
Php in 2013 (Web-5 2013 conference)
PDF
PECL Picks - Extensions to make your life better
PDF
Anatomy of a reusable module
PDF
Php Development With Eclipde PDT
PPT
Puppet
PDF
Eclipse Pdt2.0 26.05.2009
PPTX
Herd your chickens: Ansible for DB2 configuration management
PPT
Migrating PriceChirp to Rails 3.0: The Pain Points
Understanding PHP objects
Ansible : what's ansible & use case by REX
APC & Memcache the High Performance Duo
The symfony platform: Create your very own framework (PHP Quebec 2008)
Managing themes and server environments with extensible configuration arrays
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
When symfony met promises
Php on the desktop and php gtk2
Always On, Multi-Site Design Considerations
Supercharging WordPress Development in 2018
Php in 2013 (Web-5 2013 conference)
PECL Picks - Extensions to make your life better
Anatomy of a reusable module
Php Development With Eclipde PDT
Puppet
Eclipse Pdt2.0 26.05.2009
Herd your chickens: Ansible for DB2 configuration management
Migrating PriceChirp to Rails 3.0: The Pain Points
Ad

Viewers also liked (20)

PDF
Mysql开发与优化
PDF
My sql数据库开发的三十六条军规
PPT
Scrum
PPT
大型应用软件架构的变迁
PPT
淘宝分布式数据处理实践
PDF
我的Ubuntu之旅
PDF
Barcelona apc mem2010
PDF
雷志兴 百度前端基础平台与架构分享
PPT
阿里巴巴 招聘技巧培训
PPT
Daniela Barcelo Creative Director Portfolio 2014
PPT
Mysql introduction-and-performance-optimization
PDF
Designofhtml5
PDF
张克军 豆瓣前端团队的工作方式
PDF
Data on the web
PPT
杨皓 新浪博客前端架构分享
PPTX
基于Web的项目管理工具redmine
PPT
Va+Hispanic Marketing
PDF
Yui3 初探
PPT
الظواهر الجيولوجية
PDF
Tsung
Mysql开发与优化
My sql数据库开发的三十六条军规
Scrum
大型应用软件架构的变迁
淘宝分布式数据处理实践
我的Ubuntu之旅
Barcelona apc mem2010
雷志兴 百度前端基础平台与架构分享
阿里巴巴 招聘技巧培训
Daniela Barcelo Creative Director Portfolio 2014
Mysql introduction-and-performance-optimization
Designofhtml5
张克军 豆瓣前端团队的工作方式
Data on the web
杨皓 新浪博客前端架构分享
基于Web的项目管理工具redmine
Va+Hispanic Marketing
Yui3 初探
الظواهر الجيولوجية
Tsung
Ad

Similar to Dutch php conference_apc_mem2010 (20)

PPT
Zend Con 2008 Slides
PDF
Pecl Picks
ODP
Caching and tuning fun for high scalability
ODP
Caching and tuning fun for high scalability @ FrOSCon 2011
PDF
Caching with Memcached and APC
PDF
Zend Server Data Caching
ODP
phptek13 - Caching and tuning fun tutorial
ODP
Caching and tuning fun for high scalability @ phpBenelux 2011
PDF
php & performance
ODP
Caching and tuning fun for high scalability
PDF
Bottom to Top Stack Optimization with LAMP
PDF
Bottom to Top Stack Optimization - CICON2011
PDF
Give Your Site a Boost with Memcache
PDF
PHP & Performance
ODP
Caching and tuning fun for high scalability @ FOSDEM 2012
PDF
Memcached Study
ODP
Caching and tuning fun for high scalability
PPTX
PDF
Zend_Cache: how to improve the performance of PHP applications
ODP
Built-in query caching for all PHP MySQL extensions/APIs
Zend Con 2008 Slides
Pecl Picks
Caching and tuning fun for high scalability
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching with Memcached and APC
Zend Server Data Caching
phptek13 - Caching and tuning fun tutorial
Caching and tuning fun for high scalability @ phpBenelux 2011
php & performance
Caching and tuning fun for high scalability
Bottom to Top Stack Optimization with LAMP
Bottom to Top Stack Optimization - CICON2011
Give Your Site a Boost with Memcache
PHP & Performance
Caching and tuning fun for high scalability @ FOSDEM 2012
Memcached Study
Caching and tuning fun for high scalability
Zend_Cache: how to improve the performance of PHP applications
Built-in query caching for all PHP MySQL extensions/APIs

More from isnull (8)

PPT
站点报告模板
PPT
张勇 搜搜前端架构
PPT
软件工程&架构
PPT
Scrum
PPT
183银行服务器下载说明
PPT
人人网技术经理张铁安 Feed系统结构浅析
PDF
Dutch php conference_2010_opm
PPTX
易趣
站点报告模板
张勇 搜搜前端架构
软件工程&架构
Scrum
183银行服务器下载说明
人人网技术经理张铁安 Feed系统结构浅析
Dutch php conference_2010_opm
易趣

Recently uploaded (20)

PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
Teaching material agriculture food technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Encapsulation theory and applications.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
The Rise and Fall of 3GPP – Time for a Sabbatical?
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Teaching material agriculture food technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
A comparative analysis of optical character recognition models for extracting...
Per capita expenditure prediction using model stacking based on satellite ima...
NewMind AI Weekly Chronicles - August'25-Week II
Building Integrated photovoltaic BIPV_UPV.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Group 1 Presentation -Planning and Decision Making .pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Network Security Unit 5.pdf for BCA BBA.
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Encapsulation theory and applications.pdf
Machine learning based COVID-19 study performance prediction
Encapsulation_ Review paper, used for researhc scholars
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Programs and apps: productivity, graphics, security and other tools

Dutch php conference_apc_mem2010