SlideShare a Scribd company logo
REDIS FOR YOUR BOSSELENA KOLEVSKA
Who am I ?A nomad earthling. Lead developer @ www.speedtocontact.com
BLOG.ELENAKOLEVSKA.COM
@ELENA_KOLEVSKA
(Really) SHORT
INTRO
No, seriously!
REDIS IS AN OPEN SOURCE (BSD licensed),
IN-MEMORY DATA STRUCTURE STORE, USED
AS DATABASE, CACHE AND MESSAGE
BROKER
The'Definition'on redis.io
BASIC FEATURES:
▸ Different data structures
▸ Keys with a limited time-to-live
▸ Transactions
▸ Pipelining
▸ Lua scripting
▸ Pub/Sub
▸ Built-in replication
▸ Different levels of on-disk persistence
Redis for your boss
SPEED
AVAILABLE CLIENTS IN:
ActionScript bash C C# C++ Clojure
Common lisp Crystal D Dart Elixir emacs lisp
Erlang Fancy gawk GNU Prolog Go Haskell
Haxe Io Java Javascript Julia Lua
Matlab mruby Nim Node.js Objective-C OCaml
Pascal Perl PHP Pure Data Python R
Racket Rebol Ruby Rust Scala Scheme
Smalltalk Swift Tcl VB VCL
AVAILABLE DATA STRUCTURES
▸ Strings (Binary safe, can be anything from"hello world"to a jpeg file)
▸ Lists (Collections of string elements sorted according to the order of insertion)
▸ Sets (Collections of unique, unsorted string elements)
▸ Sorted sets (It's like Sets with a score)
▸ Hashes (Maps of fields associated to values. Think non-nested json objects)
▸ Bitmaps (Manipulate Strings on a bit level)
▸ HyperLogLogs (Probabilistic data structure used to estimate the cardinality of a set)
Imagine...
TWITTER ANALYSIS TOOL
▸ Track a selected group of hashtags (#gameofthrones, #got, #gotseason7)
▸ Count mentions of certain keywords ('winter is coming', 'tyrion', 'jon snow', 'stark', 'targaryen', 'cersei', 'asha greyjoy', 'Khaleesi', 'sansa', 'arya')
METRICS:
▸ A feed of all tweets containing one of the hashtags
▸ Total number of tweets with one or more of the selected hashtags
▸ A leaderboard of keyword frequency
▸ A feed of tweets per keyword
[1] CONNECTING
TO REDIS
[1] CONNECTING TO REDIS
Install the PRedis package using composer
composer require predis/predis
...
// Initialize the client
$parameters = [
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379
];
$client = new PredisClient($parameters, ['prefix' => 'twitter_stats:']);
[2] SET TRACKED
DATA
[2] SET TRACKED DATA
Use sets to store all the hashtags we'll be looking at and all the keywords
as well
$client->sadd('hashtags', 'gameofthrones','got', 'gotseason7');
// hashtags | 'gameofthrones'
// | 'got'
// | 'gotseason7'
$client->sadd('keywords', 'winter is coming', 'winterfell', 'jon snow',
'stark', 'targaryen', 'cersei', 'asha greyjoy', 'dorne', 'Khaleesi'
'hodor', 'sansa', 'arya', 'white walkers', 'the night king');
[3] GET THE DATA
[3] GET THE DATA
Use Twitter Stream API to receive notifications for tweets containing
any of the hashtags we're following
$hashtags = $client->smembers('hashtags');
// array (size=3)
// 0 => string 'got' (length=3)
// 1 => string 'gameofthrones' (length=13)
Save every new tweet from the stream as a separate String.
$keyname = 'tweet_id:' . $tweet_id;
$tweet_contents = "Winter is coming Khaleesi! #gameofthrones";
$client->set($keyname, $tweet_contents)
// 'tweet_id:45645656' | 'Winter is coming Khaleesi! #gameofthrones'
And then push to a queue to be processed asynchronously
// Use the list data structure as a queue
$client->lpush('message_queue', $keyname);
// 'message_queue' | 'tweet_id:45645656'
// | 'tweet_id:44645234'
// | 'tweet_id:43645232'
[4] WORKER TO
PROCESS THE
QUEUED JOBS
[4] WORKER TO PROCESS THE QUEUED JOBS
A separate worker will be grabbing jobs off the top of the queue and processing them:
$message_queue = $client->rpop('message_queue');
// 'message_queue' | 'tweet_id:45645656'
// | 'tweet_id:44645234'
// | 'tweet_id:43645232'
Reliable queue: RPOPLPUSH, BRPOPLPUSH
Blocking queue: BLPOP, BRPOP
[5] PROCESS THE
TWEET CONTENT
[5] PROCESS THE TWEET CONTENT
$tweet_contents = $client->get($keyname);
$keywords = $client->smembers('keywords');
foreach ($keywords as $keyword) {
$tweet_contents = strtolower($tweet_contents);
$keyword = strtolower($keyword);
if (strpos($tweet_contents,$keyword) !== false){
$client->zincrby('mention_counter', 1, $keyword); // Increase the counter for this specific keyword
// mention_counter | 'tyrion' => 9.00
// | 'the wall' => 5.00
// | 'arya' => 4.00
$keyword_feed_keyname = 'keyword_feeds:'. $keyword;
$client->lpush($keyword_feed_keyname, $tweet_contents); // Add the tweet to the keyword's feed
$client->ltrim($keyword_feed_keyname, 0, 50);
}
}
$client->incr('total_count'); // Increase the general tweet count
$client->lpush('main_feed', $tweet_contents);
$client->ltrim('main_feed', 0, 100);
[6] SHOW THE STATS
$total_count = $client->get('total_count');
// 'total_count' | 259
$scores = $client->zrevrangebyscore('mention_counter', '+inf', '-inf', ['withscores'=>1]);
// mention_counter | 'tyrion' => 9.00
// | 'the wall' => 5.00
// | 'arya' => 4.00
// Feed by keyword
foreach ($scores as $keyname => $score) {
$keyword_feeds[$keyname] = $client->lrange('keyword_feeds:' . $keyname, 0, -1);
}
// Feed of all tweets containing one of the specified hashtags
$main_feed = $client->lrange('main_feed', 0, -1);
[7] USEFUL
EXTRAS
[7] USEFUL EXTRAS
API RATE LIMIER
$ip = $_SERVER['REMOTE_ADDR'] ;
$timestamp = time(); //unix timestamp
$key = 'api_rate_limits:' . $timestamp . ':' . $ip; // $key = 'api_rate_limits:1473613000:192.168.10.1 '
$api_requests = $client->get($keyname);
if (!is_null($api_requests) && $api_requests >= 3){
throw new Exception('Too many requests per second');
}else{
$client->multi();
$client->incr($key);
$client->expire($key,10);
$client->exec();
}
[7] USEFUL EXTRAS
PIPELINING
$keyname = 'tweet_id:' . $tweet_id;
$keywords = $client->smembers('keywords');
$pipe = $client->pipeline();
$pipe->set($keyname, $tweet_contents);
foreach ($keywords as $keyword) {
[...]
}
$pipe->incr('total_count');
$pipe->lpush('main_feed', $tweet_contents);
$pipe->ltrim('main_feed', 0, 20);
$replies = $pipe->execute();
[7] USEFUL EXTRAS
LUA SCRIPTING
Thank you!
Questions?@ELENA_KOLEVSKA
HTTPS://JOIND.IN/TALK/C68B2

More Related Content

PDF
Redis for your boss 2.0
PDF
Getting Started-with-Laravel
PDF
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
PDF
Facebook的缓存系统
PDF
4069180 Caching Performance Lessons From Facebook
PPTX
A Functional Guide to Cat Herding with PHP Generators
PDF
The IoC Hydra - Dutch PHP Conference 2016
PDF
PHP 5.3 Overview
Redis for your boss 2.0
Getting Started-with-Laravel
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Facebook的缓存系统
4069180 Caching Performance Lessons From Facebook
A Functional Guide to Cat Herding with PHP Generators
The IoC Hydra - Dutch PHP Conference 2016
PHP 5.3 Overview

What's hot (20)

PDF
Zendcon 2007 Api Design
PPTX
Speed up your developments with Symfony2
PDF
Forget about index.php and build you applications around HTTP!
PPTX
New in php 7
PDF
Perl web frameworks
PPTX
Webrtc mojo
KEY
PDF
The IoC Hydra
ZIP
Web Apps in Perl - HTTP 101
KEY
CodeIgniter 3.0
PDF
Forget about Index.php and build you applications around HTTP - PHPers Cracow
KEY
Phpne august-2012-symfony-components-friends
PDF
Advanced symfony Techniques
PDF
SPL: The Missing Link in Development
ODP
Rich domain model with symfony 2.5 and doctrine 2.5
PDF
Developing apps using Perl
PDF
Symfony without the framework
PPTX
Electrify your code with PHP Generators
PDF
Php tips-and-tricks4128
PPTX
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Zendcon 2007 Api Design
Speed up your developments with Symfony2
Forget about index.php and build you applications around HTTP!
New in php 7
Perl web frameworks
Webrtc mojo
The IoC Hydra
Web Apps in Perl - HTTP 101
CodeIgniter 3.0
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Phpne august-2012-symfony-components-friends
Advanced symfony Techniques
SPL: The Missing Link in Development
Rich domain model with symfony 2.5 and doctrine 2.5
Developing apps using Perl
Symfony without the framework
Electrify your code with PHP Generators
Php tips-and-tricks4128
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Ad

Viewers also liked (20)

PDF
PHP World DC 2015 - What Can Go Wrong with Agile Development and How to Fix It
PPTX
Running Rancher and Docker on Dev Machines - Rancher Online Meetup - May 2016
PDF
90K Reasons Security is a Must - PHPWorld 2014
PDF
Salvatore Sanfilippo – How Redis Cluster works, and why - NoSQL matters Barce...
PDF
Redis for the Everyday Developer
PDF
Create, test, secure, repeat
PDF
Adding 1.21 Gigawatts to Applications with RabbitMQ (Bulgaria PHP 2016 - Tuto...
PDF
Zend Framework Foundations
PPTX
Engineer - Mastering the Art of Software
PDF
php[world] 2015 Training - Laravel from the Ground Up
PDF
Amp your site an intro to accelerated mobile pages
PDF
Hack the Future
PDF
Git Empowered
PDF
Presentation Bulgaria PHP
PDF
Code Coverage for Total Security in Application Migrations
PDF
Dip Your Toes in the Sea of Security
PDF
Console Apps: php artisan forthe:win
PPTX
Php extensions
PDF
SunshinePHP 2017 - Making the most out of MySQL
PDF
Conscious Coupling
PHP World DC 2015 - What Can Go Wrong with Agile Development and How to Fix It
Running Rancher and Docker on Dev Machines - Rancher Online Meetup - May 2016
90K Reasons Security is a Must - PHPWorld 2014
Salvatore Sanfilippo – How Redis Cluster works, and why - NoSQL matters Barce...
Redis for the Everyday Developer
Create, test, secure, repeat
Adding 1.21 Gigawatts to Applications with RabbitMQ (Bulgaria PHP 2016 - Tuto...
Zend Framework Foundations
Engineer - Mastering the Art of Software
php[world] 2015 Training - Laravel from the Ground Up
Amp your site an intro to accelerated mobile pages
Hack the Future
Git Empowered
Presentation Bulgaria PHP
Code Coverage for Total Security in Application Migrations
Dip Your Toes in the Sea of Security
Console Apps: php artisan forthe:win
Php extensions
SunshinePHP 2017 - Making the most out of MySQL
Conscious Coupling
Ad

Similar to Redis for your boss (20)

PDF
Speed up your Symfony2 application and build awesome features with Redis
PDF
Introduction to Redis
PPT
8. key value databases laboratory
PPT
Python redis talk
PDF
Redispresentation apac2012
PPTX
REDIS327
KEY
Building Scalable, Distributed Job Queues with Redis and Redis::Client
PDF
Redis & ZeroMQ: How to scale your application
PDF
Redis: Need for speed
PDF
Redis SoCraTes 2014
PDF
Redis Everywhere - Sunshine PHP
PPTX
Redis Modules - Redis India Tour - 2017
PDF
Twitter streamingapi rubymongodbv2
PDF
Consuming the Twitter Streaming API with Ruby and MongoDB
PDF
Redis everywhere - PHP London
PDF
20131008 - Wajug - TweetWall Pro
PDF
Unleashing Twitter Data for Fun and Insight
PDF
Unleashing twitter data for fun and insight
PDF
Redis — The AK-47 of Post-relational Databases
PDF
Introduction to Redis
Speed up your Symfony2 application and build awesome features with Redis
Introduction to Redis
8. key value databases laboratory
Python redis talk
Redispresentation apac2012
REDIS327
Building Scalable, Distributed Job Queues with Redis and Redis::Client
Redis & ZeroMQ: How to scale your application
Redis: Need for speed
Redis SoCraTes 2014
Redis Everywhere - Sunshine PHP
Redis Modules - Redis India Tour - 2017
Twitter streamingapi rubymongodbv2
Consuming the Twitter Streaming API with Ruby and MongoDB
Redis everywhere - PHP London
20131008 - Wajug - TweetWall Pro
Unleashing Twitter Data for Fun and Insight
Unleashing twitter data for fun and insight
Redis — The AK-47 of Post-relational Databases
Introduction to Redis

Recently uploaded (20)

PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PDF
Nekopoi APK 2025 free lastest update
PPTX
history of c programming in notes for students .pptx
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
assetexplorer- product-overview - presentation
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
System and Network Administration Chapter 2
PDF
Cost to Outsource Software Development in 2025
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
L1 - Introduction to python Backend.pptx
PDF
medical staffing services at VALiNTRY
PPTX
Computer Software and OS of computer science of grade 11.pptx
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
Nekopoi APK 2025 free lastest update
history of c programming in notes for students .pptx
Operating system designcfffgfgggggggvggggggggg
Reimagine Home Health with the Power of Agentic AI​
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
assetexplorer- product-overview - presentation
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
CHAPTER 2 - PM Management and IT Context
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
System and Network Administration Chapter 2
Cost to Outsource Software Development in 2025
Understanding Forklifts - TECH EHS Solution
L1 - Introduction to python Backend.pptx
medical staffing services at VALiNTRY
Computer Software and OS of computer science of grade 11.pptx

Redis for your boss

  • 1. REDIS FOR YOUR BOSSELENA KOLEVSKA
  • 2. Who am I ?A nomad earthling. Lead developer @ www.speedtocontact.com BLOG.ELENAKOLEVSKA.COM @ELENA_KOLEVSKA
  • 4. REDIS IS AN OPEN SOURCE (BSD licensed), IN-MEMORY DATA STRUCTURE STORE, USED AS DATABASE, CACHE AND MESSAGE BROKER The'Definition'on redis.io
  • 5. BASIC FEATURES: ▸ Different data structures ▸ Keys with a limited time-to-live ▸ Transactions ▸ Pipelining ▸ Lua scripting ▸ Pub/Sub ▸ Built-in replication ▸ Different levels of on-disk persistence
  • 8. AVAILABLE CLIENTS IN: ActionScript bash C C# C++ Clojure Common lisp Crystal D Dart Elixir emacs lisp Erlang Fancy gawk GNU Prolog Go Haskell Haxe Io Java Javascript Julia Lua Matlab mruby Nim Node.js Objective-C OCaml Pascal Perl PHP Pure Data Python R Racket Rebol Ruby Rust Scala Scheme Smalltalk Swift Tcl VB VCL
  • 9. AVAILABLE DATA STRUCTURES ▸ Strings (Binary safe, can be anything from"hello world"to a jpeg file) ▸ Lists (Collections of string elements sorted according to the order of insertion) ▸ Sets (Collections of unique, unsorted string elements) ▸ Sorted sets (It's like Sets with a score) ▸ Hashes (Maps of fields associated to values. Think non-nested json objects) ▸ Bitmaps (Manipulate Strings on a bit level) ▸ HyperLogLogs (Probabilistic data structure used to estimate the cardinality of a set)
  • 11. TWITTER ANALYSIS TOOL ▸ Track a selected group of hashtags (#gameofthrones, #got, #gotseason7) ▸ Count mentions of certain keywords ('winter is coming', 'tyrion', 'jon snow', 'stark', 'targaryen', 'cersei', 'asha greyjoy', 'Khaleesi', 'sansa', 'arya') METRICS: ▸ A feed of all tweets containing one of the hashtags ▸ Total number of tweets with one or more of the selected hashtags ▸ A leaderboard of keyword frequency ▸ A feed of tweets per keyword
  • 13. [1] CONNECTING TO REDIS Install the PRedis package using composer composer require predis/predis ... // Initialize the client $parameters = [ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379 ]; $client = new PredisClient($parameters, ['prefix' => 'twitter_stats:']);
  • 15. [2] SET TRACKED DATA Use sets to store all the hashtags we'll be looking at and all the keywords as well $client->sadd('hashtags', 'gameofthrones','got', 'gotseason7'); // hashtags | 'gameofthrones' // | 'got' // | 'gotseason7' $client->sadd('keywords', 'winter is coming', 'winterfell', 'jon snow', 'stark', 'targaryen', 'cersei', 'asha greyjoy', 'dorne', 'Khaleesi' 'hodor', 'sansa', 'arya', 'white walkers', 'the night king');
  • 16. [3] GET THE DATA
  • 17. [3] GET THE DATA Use Twitter Stream API to receive notifications for tweets containing any of the hashtags we're following $hashtags = $client->smembers('hashtags'); // array (size=3) // 0 => string 'got' (length=3) // 1 => string 'gameofthrones' (length=13)
  • 18. Save every new tweet from the stream as a separate String. $keyname = 'tweet_id:' . $tweet_id; $tweet_contents = "Winter is coming Khaleesi! #gameofthrones"; $client->set($keyname, $tweet_contents) // 'tweet_id:45645656' | 'Winter is coming Khaleesi! #gameofthrones' And then push to a queue to be processed asynchronously // Use the list data structure as a queue $client->lpush('message_queue', $keyname); // 'message_queue' | 'tweet_id:45645656' // | 'tweet_id:44645234' // | 'tweet_id:43645232'
  • 19. [4] WORKER TO PROCESS THE QUEUED JOBS
  • 20. [4] WORKER TO PROCESS THE QUEUED JOBS A separate worker will be grabbing jobs off the top of the queue and processing them: $message_queue = $client->rpop('message_queue'); // 'message_queue' | 'tweet_id:45645656' // | 'tweet_id:44645234' // | 'tweet_id:43645232' Reliable queue: RPOPLPUSH, BRPOPLPUSH Blocking queue: BLPOP, BRPOP
  • 22. [5] PROCESS THE TWEET CONTENT $tweet_contents = $client->get($keyname); $keywords = $client->smembers('keywords'); foreach ($keywords as $keyword) { $tweet_contents = strtolower($tweet_contents); $keyword = strtolower($keyword); if (strpos($tweet_contents,$keyword) !== false){ $client->zincrby('mention_counter', 1, $keyword); // Increase the counter for this specific keyword // mention_counter | 'tyrion' => 9.00 // | 'the wall' => 5.00 // | 'arya' => 4.00 $keyword_feed_keyname = 'keyword_feeds:'. $keyword; $client->lpush($keyword_feed_keyname, $tweet_contents); // Add the tweet to the keyword's feed $client->ltrim($keyword_feed_keyname, 0, 50); } } $client->incr('total_count'); // Increase the general tweet count $client->lpush('main_feed', $tweet_contents); $client->ltrim('main_feed', 0, 100);
  • 23. [6] SHOW THE STATS $total_count = $client->get('total_count'); // 'total_count' | 259 $scores = $client->zrevrangebyscore('mention_counter', '+inf', '-inf', ['withscores'=>1]); // mention_counter | 'tyrion' => 9.00 // | 'the wall' => 5.00 // | 'arya' => 4.00 // Feed by keyword foreach ($scores as $keyname => $score) { $keyword_feeds[$keyname] = $client->lrange('keyword_feeds:' . $keyname, 0, -1); } // Feed of all tweets containing one of the specified hashtags $main_feed = $client->lrange('main_feed', 0, -1);
  • 25. [7] USEFUL EXTRAS API RATE LIMIER $ip = $_SERVER['REMOTE_ADDR'] ; $timestamp = time(); //unix timestamp $key = 'api_rate_limits:' . $timestamp . ':' . $ip; // $key = 'api_rate_limits:1473613000:192.168.10.1 ' $api_requests = $client->get($keyname); if (!is_null($api_requests) && $api_requests >= 3){ throw new Exception('Too many requests per second'); }else{ $client->multi(); $client->incr($key); $client->expire($key,10); $client->exec(); }
  • 26. [7] USEFUL EXTRAS PIPELINING $keyname = 'tweet_id:' . $tweet_id; $keywords = $client->smembers('keywords'); $pipe = $client->pipeline(); $pipe->set($keyname, $tweet_contents); foreach ($keywords as $keyword) { [...] } $pipe->incr('total_count'); $pipe->lpush('main_feed', $tweet_contents); $pipe->ltrim('main_feed', 0, 20); $replies = $pipe->execute();