Scaling php applications with redis

J
Scaling PHP Applications with Redis
Josh Butts
Zendcon 2011

http://joind.in/3783
About Me

• Director of Development at Vertive, LLC


• Zend Certified in PHP 5 and ZF


• Organizer of AustinPHP


• Find me online:


  • Twitter: @jimbojsb


  • Github: jimbojsb
Agenda

• Redis Overview


• Types of keys


• PHP Strategies
What is Redis?

• Redis is an “Advanced” key-value store database


• Backed by VMWare


• Redis works like memcached, but better:


  • Atomic commands & transactions


  • Server-side data structures


  • In-memory + disk persistence
Redis in an in-memory database

• You need as much RAM as you have data


• There are no plans to improve support for “virtual” memory


• Disk persistence is exactly that


• Customize disk writes interval to suit your pain threshold


• Something interesting happens when you run out of memory
How to get Redis

• http://redis.io


• Doesn’t run (well) on Windows


   • There are a few ports out there


• Has virtually no compile dependencies


• Most distros have a package


• Make sure you’re running at least 2.2


   • 2.4.1 became stable 10/17/11
How to explore

• There aren’t any good GUI tools out there


• redis-cli is your friend
A bit about organization

• Redis can have multiple databases


  • Analogous to a MySQL database within a server instance


  • Theoretically, over 1000 databases per server


  • One data file on disk per instance


• Within a database, namespace your keys


  • Ex: myapp:mykey


  • Keep them concise but useful. Keys take memory too!
Types of Keys
String Keys             http://redis.io/commands#string

• Simple key-value


• Memcache equivalent


• Common Commands


  • SET


  • GET


  • INCR


  • STRLEN
Hash Keys                     http://redis.io/commands#hash

• Key + multiple fields / values                  • Common commands

• Like an associative array in PHP                  • HSET

• mykey => [field1 => value1, field2 => value2]     • HGET

• No nesting (unlike PHP)                           • HGETALL


                                                    • HDEL


                                                    • HVALS


                                                    • HKEYS
Hash Keys
Set Keys                            http://redis.io/commands#set

• key + unordered list of strings


• myset => [item2, item5, item1,]


• Common Commands


   • SADD


   • SMEMBERS


   • SISMEMBER


   • SREM
Set Keys
List Keys                        http://redis.io/commands#list

• Like sets, except insertion order matters


• Build queues or stacks


• Optional blocking


• Common commands


  • [B]LPUSH


  • [B]LPOP


  • LLEN
List Keys
Sorted Set Keys

• Like sets, but sorted by a user-provided score value


• Extremely fast access by score or range of scores, because it’s sorted in
  storage


• Common commands


  • ZADD


  • ZRANGE


  • ZREVRANGE
Sorted Set Keys
Other commands that work on all keys

• DEL - delete a key, regardless of type


• KEYS - search for keys (usually with a wildcard)


• EXPIRE / PERSIST - change expiration values for keys
Connecting from PHP
Connecting from PHP

• Several libraries out there


   • Rediska (http://rediska.geometria-lab.net/)


      • PHP 5.2 / ZF 1.x friendly


   • Predis (https://github.com/nrk/predis)


      • The best in my experience


      • Requires PHP 5.3
Predis

• All the examples here assume you’re using Predis


• Connect to a localhost redis: $p = new PredisClient();


• Redis commands implemented as magic methods on Client();


• $p->set($key, $val);


• $val = $p->get($key);
Attribute Display Logic

                                             items_attributes
                         items
                                                id INT(11)

                       id INT(11)             item_id INT(11)

                                          attr_name VARCHAR(32)
                   name VARCHAR(32)
                                          attr_value VARCHAR(32)



                   10k rows               100k rows
• An item, a Dell Latitude Laptop, has:


  • Free Shipping, Financing Available, Expires Soon, etc
Attribute Display Logic

   • Display “Free Shipping” graphic on the item if it has a free
     shipping attribute row




                        50 items per page
Attribute Display - Traditional

  class Item
  {
     public function hasAttribute($name)
     {
       $sql = "SELECT 1
             FROM items_attributes
             WHERE item_id = $this->id
             AND attr_name='$name'
             LIMIT 1";
       $result = $this->pdo->execute($sql);
       return $result != false;
     }
  }
Denormalize data from MySQL to Redis

• Smart caching


• Define a consistent way to represent a relational object in Redis


  • I prefer [object class]:[object id]:[attribute]


  • ex: product:13445:num_comments


  • This prevents data collisions, and makes it easy to work with data on
    the command line
Attribute Display - Redis


class Item
{
   public function hasAttribute($name)
   {
     return $this->redis->sismember(“item:$this->id:attributes”, $name);
   }

    public function addAttribute($name, $value)
    {
      //traditional mysql stuff here still
      $this->redis->sadd('item:45:attributes', $name);
    }
}
Advantages

• The more items you have, the less MySQL will scale this solution for you on
  it’s own


• Frequently updating your items kills the MySQL query cache


• Checking existence of a set member is O(1) time


• On a laptop, I can check roughly 10,000 attributes per second
Session Clustering



      WEB - 1             WEB - 2         WEB - 3

      PHP Sessions       PHP Sessions     PHP Sessions




                     Inconsistent state
Session Clustering



       WEB - 1        WEB - 2        WEB - 3




                       DB - 1

                     PHP Sessions


Slow with many users (never cached), replication lag
Session Clustering



      WEB - 1              WEB - 2        WEB - 3




           REDIS - 1                 DB - 1

            PHP Sessions



   Constant time lookups, in-memory sessions
Job Queues

• Redis lists make great job queues


• Offload your intensive workloads to some other process


• Blocking I/O allows you to easily build long-running daemons
Job Queues

class Queue
{
   protected $name;
   protected $predis;

    public function push(Array $job)
    {
      $this->predis->lpush($this->name, json_encode($job));
    }

    public function pop($block = false)
    {
      $job = null;
      if ($block) {
          $data = $this->predis->brpop($this->name, 0);
          $job = $data[1];
      } else {
          $job = $this->predis->rpop($this->name);
      }
      if ($job) {
          return json_decode($job);
      }
    }
}
Queuing Jobs

$q = new Queue('test_queue');
$form = new My_Zend_Form();
if ($form->isValid($_POST)) {

    $q->push($form->getValues());
    $message = “Thanks for your submission”;

} else {

    $message = “Error - something went wrong”;

}

echo “<h1>$message</h1>”;
Processing Jobs - Crontab style

 function processJob(Array $job)
 {
    //...something really cool here
    // throw an exception on error
 }

 // process all pending jobs
 $q = new Queue(‘test_queue’);
 while ($job = $q->pop()) {
    try {
            processJob($job);
        } catch (Exception $e) {
           Echo “error processing job”;
           $q = new Queue(‘errors’);
           $q->push($job);
        }
 }
Processing Jobs - Worker style

function processJob(Array $job)
{
   //...something really cool here
   // throw an exception on error
}

// keep processing jobs as they become available
$q = new Queue(‘test_queue’);
while ($job = $q->pop(true)) {
   try {
           processJob($job);
       } catch (Exception $e) {
          Echo “error processing job”;
          $q = new Queue(‘errors’);
          $q->push($job);
       }
}
MVC Routing

• Example:


  • Offers.com has about 3900 stores


  • Store pages live at /[store]/
Old Store Routing


 class Store_Route
 {
    public function route($url)
    {
      $sql = “SELECT id, type
                        FROM stores
                        WHERE url=’$url’”;
      $store = $this->pdo->execute($sql);
      //... do logic to determine what action to use based on type ...//
            return array(“module”     => “core”,
                             “controller” => “store”,
                             “action”    => $action);
    }
 }




• And then there’s offers.com/[holiday]/....
New Routing


class Redis_Route
{
   public function route($url)
   {
     $p = $this->predis;
     if ($p->exists($url)) {

          list($module, $controller, $action) = $this->redis->hVals($url);
          return array(“module”    => $module,
                   “controller” => $controller,
                   “action”    => $action);
        }
        return false;
    }
}
Filling in the Redis keys




 class Store
 {
    public function create(Array $data)
    {
           // ... traditional SQL stuff to put store in the database ... //
         $route = array(“module” => “core”,
                           “controller” => “store”,
                           “action” => $data[“type”]);
           $this->predis->hmset($data[“url”], $route);
    }
 }
Advantages

• I can now create offers.com/[anything]/ and route it to the right place, in
  O(1) time


• I’m only adding a few lines of code to my existing models
Questions?
http://joind.in/3783
Vertive is Hiring

• We help people save money


• We’re looking for engineers in Austin, TX to work on:
1 of 44

Recommended

Redis in Practice: Scenarios, Performance and Practice with PHP by
Redis in Practice: Scenarios, Performance and Practice with PHPRedis in Practice: Scenarios, Performance and Practice with PHP
Redis in Practice: Scenarios, Performance and Practice with PHPChen Huang
1.6K views24 slides
Everything you always wanted to know about Redis but were afraid to ask by
Everything you always wanted to know about Redis but were afraid to askEverything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askCarlos Abalde
26.9K views73 slides
Redis 101 by
Redis 101Redis 101
Redis 101Geoff Hoffman
16.8K views61 slides
Building Scalable, Distributed Job Queues with Redis and Redis::Client by
Building Scalable, Distributed Job Queues with Redis and Redis::ClientBuilding Scalable, Distributed Job Queues with Redis and Redis::Client
Building Scalable, Distributed Job Queues with Redis and Redis::ClientMike Friedman
18K views66 slides
Redis Indices (#RedisTLV) by
Redis Indices (#RedisTLV)Redis Indices (#RedisTLV)
Redis Indices (#RedisTLV)Itamar Haber
5.6K views42 slides
Redis — The AK-47 of Post-relational Databases by
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesKarel Minarik
23.5K views70 slides

More Related Content

What's hot

Redis and it's data types by
Redis and it's data typesRedis and it's data types
Redis and it's data typesAniruddha Chakrabarti
2.5K views44 slides
Speed up your Symfony2 application and build awesome features with Redis by
Speed up your Symfony2 application and build awesome features with RedisSpeed up your Symfony2 application and build awesome features with Redis
Speed up your Symfony2 application and build awesome features with RedisRicard Clau
27.7K views52 slides
Introduction to redis - version 2 by
Introduction to redis - version 2Introduction to redis - version 2
Introduction to redis - version 2Dvir Volk
9.9K views21 slides
Redis Use Patterns (DevconTLV June 2014) by
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Itamar Haber
12.9K views25 slides
Redis memcached pdf by
Redis memcached pdfRedis memcached pdf
Redis memcached pdfErin O'Neill
26.2K views63 slides
Redis introduction by
Redis introductionRedis introduction
Redis introductionFederico Daniel Colombo Gennarelli
5.9K views22 slides

What's hot(20)

Speed up your Symfony2 application and build awesome features with Redis by Ricard Clau
Speed up your Symfony2 application and build awesome features with RedisSpeed up your Symfony2 application and build awesome features with Redis
Speed up your Symfony2 application and build awesome features with Redis
Ricard Clau27.7K views
Introduction to redis - version 2 by Dvir Volk
Introduction to redis - version 2Introduction to redis - version 2
Introduction to redis - version 2
Dvir Volk9.9K views
Redis Use Patterns (DevconTLV June 2014) by Itamar Haber
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)
Itamar Haber12.9K views
Redis memcached pdf by Erin O'Neill
Redis memcached pdfRedis memcached pdf
Redis memcached pdf
Erin O'Neill26.2K views
Redis in Practice by Noah Davis
Redis in PracticeRedis in Practice
Redis in Practice
Noah Davis19.8K views
An Introduction to REDIS NoSQL database by Ali MasudianPour
An Introduction to REDIS NoSQL databaseAn Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL database
Ali MasudianPour5.4K views
Redis/Lessons learned by Tit Petric
Redis/Lessons learnedRedis/Lessons learned
Redis/Lessons learned
Tit Petric7.4K views
Boosting Machine Learning with Redis Modules and Spark by Dvir Volk
Boosting Machine Learning with Redis Modules and SparkBoosting Machine Learning with Redis Modules and Spark
Boosting Machine Learning with Redis Modules and Spark
Dvir Volk2.1K views
Extend Redis with Modules by Itamar Haber
Extend Redis with ModulesExtend Redis with Modules
Extend Redis with Modules
Itamar Haber2K views
Kicking ass with redis by Dvir Volk
Kicking ass with redisKicking ass with redis
Kicking ass with redis
Dvir Volk39.1K views

Viewers also liked

How to scale PHP applications by
How to scale PHP applicationsHow to scale PHP applications
How to scale PHP applicationsEnrico Zimuel
29.5K views39 slides
PHP High Availability High Performance by
PHP High Availability High PerformancePHP High Availability High Performance
PHP High Availability High PerformanceAmazee Labs
13K views121 slides
(micro)services avec Symfony et Tolerance by
(micro)services avec Symfony et Tolerance(micro)services avec Symfony et Tolerance
(micro)services avec Symfony et ToleranceSamuel ROZE
910 views58 slides
Architechture of a social network for 30M users by
Architechture of a social network for 30M usersArchitechture of a social network for 30M users
Architechture of a social network for 30M usersFotostrana
567 views50 slides
Slide Seminar PHP Indonesia - NoSQL Redis by
Slide Seminar PHP Indonesia - NoSQL RedisSlide Seminar PHP Indonesia - NoSQL Redis
Slide Seminar PHP Indonesia - NoSQL Redisrifqi alfian
2.1K views18 slides
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P... by
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Pantheon
1.1K views85 slides

Viewers also liked(20)

How to scale PHP applications by Enrico Zimuel
How to scale PHP applicationsHow to scale PHP applications
How to scale PHP applications
Enrico Zimuel29.5K views
PHP High Availability High Performance by Amazee Labs
PHP High Availability High PerformancePHP High Availability High Performance
PHP High Availability High Performance
Amazee Labs13K views
(micro)services avec Symfony et Tolerance by Samuel ROZE
(micro)services avec Symfony et Tolerance(micro)services avec Symfony et Tolerance
(micro)services avec Symfony et Tolerance
Samuel ROZE910 views
Architechture of a social network for 30M users by Fotostrana
Architechture of a social network for 30M usersArchitechture of a social network for 30M users
Architechture of a social network for 30M users
Fotostrana567 views
Slide Seminar PHP Indonesia - NoSQL Redis by rifqi alfian
Slide Seminar PHP Indonesia - NoSQL RedisSlide Seminar PHP Indonesia - NoSQL Redis
Slide Seminar PHP Indonesia - NoSQL Redis
rifqi alfian2.1K views
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P... by Pantheon
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Pantheon1.1K views
Redis Everywhere - Sunshine PHP by Ricard Clau
Redis Everywhere - Sunshine PHPRedis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHP
Ricard Clau22.5K views
NoSQL in MySQL by Ulf Wendel
NoSQL in MySQLNoSQL in MySQL
NoSQL in MySQL
Ulf Wendel23.2K views
Beyond relational database - Building high performance websites using Redis a... by Dinh Pham
Beyond relational database - Building high performance websites using Redis a...Beyond relational database - Building high performance websites using Redis a...
Beyond relational database - Building high performance websites using Redis a...
Dinh Pham2.7K views
MOSC2012 - Building High-Performance Web-Application with PHP & MongoDB by r1dotmy
MOSC2012 - Building High-Performance Web-Application with PHP & MongoDBMOSC2012 - Building High-Performance Web-Application with PHP & MongoDB
MOSC2012 - Building High-Performance Web-Application with PHP & MongoDB
r1dotmy2.1K views
Docker deploy by Eric Ahn
Docker deployDocker deploy
Docker deploy
Eric Ahn398 views
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015 by Innomatic Platform
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Innomatic Platform7.9K views
Frontera: open source, large scale web crawling framework by Scrapinghub
Frontera: open source, large scale web crawling frameworkFrontera: open source, large scale web crawling framework
Frontera: open source, large scale web crawling framework
Scrapinghub5.9K views
Scaling PHP to 40 Million Uniques by Jonathan Klein
Scaling PHP to 40 Million UniquesScaling PHP to 40 Million Uniques
Scaling PHP to 40 Million Uniques
Jonathan Klein7.3K views
RestMQ - HTTP/Redis based Message Queue by Gleicon Moraes
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message Queue
Gleicon Moraes121.4K views
PHP with Service BUS (RabbitMQ/Redis/MongoDB) - IMasters PHP Experience 2016 by Alexandre Brandão Lustosa
PHP with Service BUS (RabbitMQ/Redis/MongoDB) - IMasters PHP Experience 2016PHP with Service BUS (RabbitMQ/Redis/MongoDB) - IMasters PHP Experience 2016
PHP with Service BUS (RabbitMQ/Redis/MongoDB) - IMasters PHP Experience 2016
Redis everywhere - PHP London by Ricard Clau
Redis everywhere - PHP LondonRedis everywhere - PHP London
Redis everywhere - PHP London
Ricard Clau28K views
Magento scalability from the trenches (Meet Magento Sweden 2016) by Divante
Magento scalability from the trenches (Meet Magento Sweden 2016)Magento scalability from the trenches (Meet Magento Sweden 2016)
Magento scalability from the trenches (Meet Magento Sweden 2016)
Divante166.5K views
Authentication: Cookies vs JWTs and why you’re doing it wrong by Derek Perkins
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrong
Derek Perkins35K views

Similar to Scaling php applications with redis

PHP Basics and Demo HackU by
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackUAnshu Prateek
407 views17 slides
Fatc by
FatcFatc
FatcWade Arnold
925 views45 slides
Advanced Php - Macq Electronique 2010 by
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
3.8K views88 slides
Php summary by
Php summaryPhp summary
Php summaryMichelle Darling
2.5K views25 slides
Redis the better NoSQL by
Redis the better NoSQLRedis the better NoSQL
Redis the better NoSQLOpenFest team
1.2K views25 slides
Php by
PhpPhp
Phpayushchugh47
462 views23 slides

Similar to Scaling php applications with redis(20)

PHP Basics and Demo HackU by Anshu Prateek
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackU
Anshu Prateek407 views
Redis the better NoSQL by OpenFest team
Redis the better NoSQLRedis the better NoSQL
Redis the better NoSQL
OpenFest team1.2K views
Supercharging WordPress Development in 2018 by Adam Tomat
Supercharging WordPress Development in 2018Supercharging WordPress Development in 2018
Supercharging WordPress Development in 2018
Adam Tomat212 views
Performance tuning with zend framework by Alan Seiden
Performance tuning with zend frameworkPerformance tuning with zend framework
Performance tuning with zend framework
Alan Seiden7.7K views
Working with databases in Perl by Laurent Dami
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
Laurent Dami4.6K views
Introducing PHP Data Objects by webhostingguy
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
webhostingguy760 views
Building Testable PHP Applications by chartjes
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes7.4K views
Drupal II: The SQL by ddiers
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
ddiers3.1K views
Zend Framework 1 + Doctrine 2 by Ralph Schindler
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2
Ralph Schindler6.8K views
Php course-in-navimumbai by vibrantuser
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbai
vibrantuser84 views
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku by Redis Labs
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Redis Labs2.4K views
PHP from soup to nuts Course Deck by rICh morrow
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
rICh morrow2.2K views
MIND sweeping introduction to PHP by BUDNET
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
BUDNET2K views

More from jimbojsb

Fall 2011 PHP Class - Session 2 by
Fall 2011 PHP Class - Session 2Fall 2011 PHP Class - Session 2
Fall 2011 PHP Class - Session 2jimbojsb
573 views21 slides
Fall 2011 PHP Class - Session 1 by
Fall 2011 PHP Class - Session 1Fall 2011 PHP Class - Session 1
Fall 2011 PHP Class - Session 1jimbojsb
443 views25 slides
Austin NoSQL 2011-07-06 by
Austin NoSQL 2011-07-06Austin NoSQL 2011-07-06
Austin NoSQL 2011-07-06jimbojsb
495 views93 slides
GeekAustin PHP Class - Session 7 by
GeekAustin PHP Class - Session 7GeekAustin PHP Class - Session 7
GeekAustin PHP Class - Session 7jimbojsb
400 views7 slides
GeekAustin PHP Class - Session 6 by
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6jimbojsb
1K views14 slides
Geek Austin PHP Class - Session 4 by
Geek Austin PHP Class - Session 4Geek Austin PHP Class - Session 4
Geek Austin PHP Class - Session 4jimbojsb
532 views14 slides

More from jimbojsb(9)

Fall 2011 PHP Class - Session 2 by jimbojsb
Fall 2011 PHP Class - Session 2Fall 2011 PHP Class - Session 2
Fall 2011 PHP Class - Session 2
jimbojsb573 views
Fall 2011 PHP Class - Session 1 by jimbojsb
Fall 2011 PHP Class - Session 1Fall 2011 PHP Class - Session 1
Fall 2011 PHP Class - Session 1
jimbojsb443 views
Austin NoSQL 2011-07-06 by jimbojsb
Austin NoSQL 2011-07-06Austin NoSQL 2011-07-06
Austin NoSQL 2011-07-06
jimbojsb495 views
GeekAustin PHP Class - Session 7 by jimbojsb
GeekAustin PHP Class - Session 7GeekAustin PHP Class - Session 7
GeekAustin PHP Class - Session 7
jimbojsb400 views
GeekAustin PHP Class - Session 6 by jimbojsb
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6
jimbojsb1K views
Geek Austin PHP Class - Session 4 by jimbojsb
Geek Austin PHP Class - Session 4Geek Austin PHP Class - Session 4
Geek Austin PHP Class - Session 4
jimbojsb532 views
Geek Austin PHP Class - Session 3 by jimbojsb
Geek Austin PHP Class - Session 3Geek Austin PHP Class - Session 3
Geek Austin PHP Class - Session 3
jimbojsb757 views
Geek Austin PHP Class - Session 2 by jimbojsb
Geek Austin PHP Class - Session 2Geek Austin PHP Class - Session 2
Geek Austin PHP Class - Session 2
jimbojsb580 views
Geek Austin PHP Class - Session 1 by jimbojsb
Geek Austin PHP Class - Session 1Geek Austin PHP Class - Session 1
Geek Austin PHP Class - Session 1
jimbojsb429 views

Recently uploaded

Ransomware is Knocking your Door_Final.pdf by
Ransomware is Knocking your Door_Final.pdfRansomware is Knocking your Door_Final.pdf
Ransomware is Knocking your Door_Final.pdfSecurity Bootcamp
55 views46 slides
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdfDr. Jimmy Schwarzkopf
19 views29 slides
PRODUCT PRESENTATION.pptx by
PRODUCT PRESENTATION.pptxPRODUCT PRESENTATION.pptx
PRODUCT PRESENTATION.pptxangelicacueva6
14 views1 slide
Design Driven Network Assurance by
Design Driven Network AssuranceDesign Driven Network Assurance
Design Driven Network AssuranceNetwork Automation Forum
15 views42 slides
Info Session November 2023.pdf by
Info Session November 2023.pdfInfo Session November 2023.pdf
Info Session November 2023.pdfAleksandraKoprivica4
12 views15 slides

Recently uploaded(20)

STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by Dr. Jimmy Schwarzkopf
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf
Serverless computing with Google Cloud (2023-24) by wesley chun
Serverless computing with Google Cloud (2023-24)Serverless computing with Google Cloud (2023-24)
Serverless computing with Google Cloud (2023-24)
wesley chun11 views
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec12 views
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by Jasper Oosterveld
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi127 views
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman33 views
Attacking IoT Devices from a Web Perspective - Linux Day by Simone Onofri
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
Simone Onofri16 views

Scaling php applications with redis

  • 1. Scaling PHP Applications with Redis Josh Butts Zendcon 2011 http://joind.in/3783
  • 2. About Me • Director of Development at Vertive, LLC • Zend Certified in PHP 5 and ZF • Organizer of AustinPHP • Find me online: • Twitter: @jimbojsb • Github: jimbojsb
  • 3. Agenda • Redis Overview • Types of keys • PHP Strategies
  • 4. What is Redis? • Redis is an “Advanced” key-value store database • Backed by VMWare • Redis works like memcached, but better: • Atomic commands & transactions • Server-side data structures • In-memory + disk persistence
  • 5. Redis in an in-memory database • You need as much RAM as you have data • There are no plans to improve support for “virtual” memory • Disk persistence is exactly that • Customize disk writes interval to suit your pain threshold • Something interesting happens when you run out of memory
  • 6. How to get Redis • http://redis.io • Doesn’t run (well) on Windows • There are a few ports out there • Has virtually no compile dependencies • Most distros have a package • Make sure you’re running at least 2.2 • 2.4.1 became stable 10/17/11
  • 7. How to explore • There aren’t any good GUI tools out there • redis-cli is your friend
  • 8. A bit about organization • Redis can have multiple databases • Analogous to a MySQL database within a server instance • Theoretically, over 1000 databases per server • One data file on disk per instance • Within a database, namespace your keys • Ex: myapp:mykey • Keep them concise but useful. Keys take memory too!
  • 10. String Keys http://redis.io/commands#string • Simple key-value • Memcache equivalent • Common Commands • SET • GET • INCR • STRLEN
  • 11. Hash Keys http://redis.io/commands#hash • Key + multiple fields / values • Common commands • Like an associative array in PHP • HSET • mykey => [field1 => value1, field2 => value2] • HGET • No nesting (unlike PHP) • HGETALL • HDEL • HVALS • HKEYS
  • 13. Set Keys http://redis.io/commands#set • key + unordered list of strings • myset => [item2, item5, item1,] • Common Commands • SADD • SMEMBERS • SISMEMBER • SREM
  • 15. List Keys http://redis.io/commands#list • Like sets, except insertion order matters • Build queues or stacks • Optional blocking • Common commands • [B]LPUSH • [B]LPOP • LLEN
  • 17. Sorted Set Keys • Like sets, but sorted by a user-provided score value • Extremely fast access by score or range of scores, because it’s sorted in storage • Common commands • ZADD • ZRANGE • ZREVRANGE
  • 19. Other commands that work on all keys • DEL - delete a key, regardless of type • KEYS - search for keys (usually with a wildcard) • EXPIRE / PERSIST - change expiration values for keys
  • 21. Connecting from PHP • Several libraries out there • Rediska (http://rediska.geometria-lab.net/) • PHP 5.2 / ZF 1.x friendly • Predis (https://github.com/nrk/predis) • The best in my experience • Requires PHP 5.3
  • 22. Predis • All the examples here assume you’re using Predis • Connect to a localhost redis: $p = new PredisClient(); • Redis commands implemented as magic methods on Client(); • $p->set($key, $val); • $val = $p->get($key);
  • 23. Attribute Display Logic items_attributes items id INT(11) id INT(11) item_id INT(11) attr_name VARCHAR(32) name VARCHAR(32) attr_value VARCHAR(32) 10k rows 100k rows • An item, a Dell Latitude Laptop, has: • Free Shipping, Financing Available, Expires Soon, etc
  • 24. Attribute Display Logic • Display “Free Shipping” graphic on the item if it has a free shipping attribute row 50 items per page
  • 25. Attribute Display - Traditional class Item { public function hasAttribute($name) { $sql = "SELECT 1 FROM items_attributes WHERE item_id = $this->id AND attr_name='$name' LIMIT 1"; $result = $this->pdo->execute($sql); return $result != false; } }
  • 26. Denormalize data from MySQL to Redis • Smart caching • Define a consistent way to represent a relational object in Redis • I prefer [object class]:[object id]:[attribute] • ex: product:13445:num_comments • This prevents data collisions, and makes it easy to work with data on the command line
  • 27. Attribute Display - Redis class Item { public function hasAttribute($name) { return $this->redis->sismember(“item:$this->id:attributes”, $name); } public function addAttribute($name, $value) { //traditional mysql stuff here still $this->redis->sadd('item:45:attributes', $name); } }
  • 28. Advantages • The more items you have, the less MySQL will scale this solution for you on it’s own • Frequently updating your items kills the MySQL query cache • Checking existence of a set member is O(1) time • On a laptop, I can check roughly 10,000 attributes per second
  • 29. Session Clustering WEB - 1 WEB - 2 WEB - 3 PHP Sessions PHP Sessions PHP Sessions Inconsistent state
  • 30. Session Clustering WEB - 1 WEB - 2 WEB - 3 DB - 1 PHP Sessions Slow with many users (never cached), replication lag
  • 31. Session Clustering WEB - 1 WEB - 2 WEB - 3 REDIS - 1 DB - 1 PHP Sessions Constant time lookups, in-memory sessions
  • 32. Job Queues • Redis lists make great job queues • Offload your intensive workloads to some other process • Blocking I/O allows you to easily build long-running daemons
  • 33. Job Queues class Queue { protected $name; protected $predis; public function push(Array $job) { $this->predis->lpush($this->name, json_encode($job)); } public function pop($block = false) { $job = null; if ($block) { $data = $this->predis->brpop($this->name, 0); $job = $data[1]; } else { $job = $this->predis->rpop($this->name); } if ($job) { return json_decode($job); } } }
  • 34. Queuing Jobs $q = new Queue('test_queue'); $form = new My_Zend_Form(); if ($form->isValid($_POST)) { $q->push($form->getValues()); $message = “Thanks for your submission”; } else { $message = “Error - something went wrong”; } echo “<h1>$message</h1>”;
  • 35. Processing Jobs - Crontab style function processJob(Array $job) { //...something really cool here // throw an exception on error } // process all pending jobs $q = new Queue(‘test_queue’); while ($job = $q->pop()) { try { processJob($job); } catch (Exception $e) { Echo “error processing job”; $q = new Queue(‘errors’); $q->push($job); } }
  • 36. Processing Jobs - Worker style function processJob(Array $job) { //...something really cool here // throw an exception on error } // keep processing jobs as they become available $q = new Queue(‘test_queue’); while ($job = $q->pop(true)) { try { processJob($job); } catch (Exception $e) { Echo “error processing job”; $q = new Queue(‘errors’); $q->push($job); } }
  • 37. MVC Routing • Example: • Offers.com has about 3900 stores • Store pages live at /[store]/
  • 38. Old Store Routing class Store_Route { public function route($url) { $sql = “SELECT id, type FROM stores WHERE url=’$url’”; $store = $this->pdo->execute($sql); //... do logic to determine what action to use based on type ...// return array(“module” => “core”, “controller” => “store”, “action” => $action); } } • And then there’s offers.com/[holiday]/....
  • 39. New Routing class Redis_Route { public function route($url) { $p = $this->predis; if ($p->exists($url)) { list($module, $controller, $action) = $this->redis->hVals($url); return array(“module” => $module, “controller” => $controller, “action” => $action); } return false; } }
  • 40. Filling in the Redis keys class Store { public function create(Array $data) { // ... traditional SQL stuff to put store in the database ... // $route = array(“module” => “core”, “controller” => “store”, “action” => $data[“type”]); $this->predis->hmset($data[“url”], $route); } }
  • 41. Advantages • I can now create offers.com/[anything]/ and route it to the right place, in O(1) time • I’m only adding a few lines of code to my existing models
  • 44. Vertive is Hiring • We help people save money • We’re looking for engineers in Austin, TX to work on:

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. Can do increment, etc on individual fields\n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n