SlideShare a Scribd company logo
Redis in Practice
• Why Redis
• How to make Redis Faster
• Replication and Sentinel
Chen Huang
c.huang@*****.com
Content
• Why Redis
 Comparison of In-Memory Storages
 Scenarios
 Sharding (Parallel Scaling)
• How to make Redis Faster
• Replication and Sentinel
Comparison of In-Memory Storages
Redis Memcached MemSQL
Data Structure
Key-Value, List,
Hash, Set, Z-Set Key-Value Relational
Concurrency Poor Good Good
Sharding
Not Generally
Available Yes Yes
Transaction Optimistic Lock CAS No
Scripting Lua No No
Replication Yes Repcached Yes
Persistance Yes MemcacheDB Yes
High Availability Redis Sentinel ? ?
Scenarios
• Cache
Java:
Map cache = new LinkedHashMap() {
protected boolean removeEldestEntry(Map.Entry eldest) {
return isTimeout(eldest);
}
}
Redis:
SETEX key timeout value
Scenarios
• List / Queue
Java Redis
LinkedList / ArrayDeque List
list.offerFirst(element) LPUSH list element
list.offerLast(element) RPUSH list element
list.pollFirst() LPOP list
list.pollLast() RPOP list
• Session
[Servlet API]
HttpSession session = req.getSession(); // got by session id
Object oldValue = session.getAttribute(key);
session.setAttribute(key, newValue);
[Implementation]
Scenarios
Java Redis
HashMap<String, HashMap> Hash
map.get(id).get(key); HGET id key
map.get(id).put(key, value); HSET id key value
Scenarios
• Session Timeout
[Servlet API]
session.set(key, new HttpSessionBindingListener() {
public void valueUnbound(HttpSessionBindingEvent event) {
// Trigger Timeout Event
}
});
[Implementation]
Java Redis
LinkedHashMap Hash + Sorted Set (ZSet)
Iterator i = map.values().iterator();
while (i.hasNext() &&
isTimeout(i.next())) {
// Trigger Timeout Event
i.remove();
}
ZRANGEBYSCORE zset 0 now
// Trigger Timeout Event
HDEL id, id, ...
ZREMRANGEBYSCORE zset 0 now
Sharding (Parallel Scaling)
• Redis is Single-Threaded
• Multiple Redis Instances in one Server
• Partition by Hash of Keys
Content
• Why Redis
• How to make Redis Faster
 Time Complexity
 Communication Latency
 Serialization
• Replication and Sentinel
Time Complexity
See Redis Documentation for more Details
Structure Operation Complexity
Hash HGET id key
Key-Value GET id
Key-Value KEYS prefix*
List LPUSH/LPOP
List LINDEX/LSET
Sorted Set ZADD
Sorted Set ZRANGEBYSCORE
O(1)
O(1)
O(n)
O(1)
O(n)
O(log(n))
O(log(n)
+m)
Communication Latency
• Massive (Multi-Row) Insertion
[SQL]
× INSERT INTO cache (key, value) VALUES ("key1",
"value1");
INSERT INTO cache (key, value) VALUES ("key2",
"value2");
...
√ INSERT INTO cache (key, value) VALUES ("key1",
"value1"),
("key2", "value2"), ("key3", "value3"), ...
[Redis]
× HSET cache key1 value1
HSET cache key2 value2
...
√ HMSET cache key1 value1 key2 value2 ...
Communication Latency
• Pipeline (Batch)
Communication Latency
• Pipeline (Batch)
[SQL in Java]
try (Statement stmt = conn.createStatement()) {
stmt.addBatch("INSERT INTO cache1 ...");
stmt.addBatch("INSERT INTO cache2 ...");
stmt.executeBatch();
}
[Redis in Java]
Pipeline pl = jedis.pipelined();
pl.hset("cache1", "key1", "value1");
pl.hset("cache2", "key2", "value2");
pl.sync();
Communication Latency
• Scripting
[Java]
int balance = Integer.parseInt(jedis.get("balance"));
if (balance > 100) {
jedis.set("balance", Integer.toString(balance - 100));
}
[Lua]
local i = tonumber(redis.call('get', 'balance'))
if i > 100 then
redis.call('set', 'balance', tostring(i - 100))
end
Communication Latency
• SQL Efficiency
Multi-Row Insertion > Batch > Stored Procedure
• Redis Efficiency
Massive Insertion > Pipeline > Scripting
Serialization
Serialization
Serialization
• Kryo vs. Protobuf
Content
• Why Redis
• How to make Redis Faster
• Replication and Sentinel
 Replication
 Sentinel
 Practice with PHP
Replication
Master
Slave-1
Slave-2
Slave-3
Web Server
Write
Sync to
Sync to
Sync to
Web Server
Read
Read
Read
Sentinel
A
B
C
D
X
B
C
D
A
Sentinels Sentinels
Sync from
Sync from
Practice with PHP
Shard 1 Shard 2
Sentinels
Shard 3 Shard 4
Web Server
Config Center
Write
Read
Scheduled Config Sync
Web Server
Web Server
redis.config.php
redis.config.php
redis.config.php
redis.config.php
Scheduled Config Sync
Practice with PHP
References
• Redis
http://redis.io/
• phpredis
https://github.com/phpredis/phpredis
Ad

More Related Content

What's hot (20)

Redis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational Databases
Karel Minarik
 
Redis overview for Software Architecture Forum
Redis overview for Software Architecture ForumRedis overview for Software Architecture Forum
Redis overview for Software Architecture Forum
Christopher Spring
 
Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)
Felix Geisendörfer
 
Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3
Felix Geisendörfer
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
Felix Geisendörfer
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)
Itamar Haber
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
Felix Geisendörfer
 
Caching solutions with Redis
Caching solutions   with RedisCaching solutions   with Redis
Caching solutions with Redis
George Platon
 
Redis in Practice
Redis in PracticeRedis in Practice
Redis in Practice
Noah Davis
 
Redis basics
Redis basicsRedis basics
Redis basics
Arthur Shvetsov
 
Redis and it's data types
Redis and it's data typesRedis and it's data types
Redis and it's data types
Aniruddha Chakrabarti
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
Dvir Volk
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
Felix Geisendörfer
 
Paris Redis Meetup Introduction
Paris Redis Meetup IntroductionParis Redis Meetup Introduction
Paris Redis Meetup Introduction
Gregory Boissinot
 
Redis and its many use cases
Redis and its many use casesRedis and its many use cases
Redis and its many use cases
Christian Joudrey
 
Memcached Study
Memcached StudyMemcached Study
Memcached Study
nam kwangjin
 
ELK stack at weibo.com
ELK stack at weibo.comELK stack at weibo.com
ELK stack at weibo.com
琛琳 饶
 
{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4
琛琳 饶
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
Felix Geisendörfer
 
DBD::Gofer 200809
DBD::Gofer 200809DBD::Gofer 200809
DBD::Gofer 200809
Tim Bunce
 
Redis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational Databases
Karel Minarik
 
Redis overview for Software Architecture Forum
Redis overview for Software Architecture ForumRedis overview for Software Architecture Forum
Redis overview for Software Architecture Forum
Christopher Spring
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)
Itamar Haber
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
Felix Geisendörfer
 
Caching solutions with Redis
Caching solutions   with RedisCaching solutions   with Redis
Caching solutions with Redis
George Platon
 
Redis in Practice
Redis in PracticeRedis in Practice
Redis in Practice
Noah Davis
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
Dvir Volk
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
Felix Geisendörfer
 
Paris Redis Meetup Introduction
Paris Redis Meetup IntroductionParis Redis Meetup Introduction
Paris Redis Meetup Introduction
Gregory Boissinot
 
Redis and its many use cases
Redis and its many use casesRedis and its many use cases
Redis and its many use cases
Christian Joudrey
 
ELK stack at weibo.com
ELK stack at weibo.comELK stack at weibo.com
ELK stack at weibo.com
琛琳 饶
 
{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4
琛琳 饶
 
DBD::Gofer 200809
DBD::Gofer 200809DBD::Gofer 200809
DBD::Gofer 200809
Tim Bunce
 

Viewers also liked (8)

MOSC2012 - Building High-Performance Web-Application with PHP & MongoDB
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
r1dotmy
 
Key-value databases in practice Redis @ DotNetToscana
Key-value databases in practice Redis @ DotNetToscanaKey-value databases in practice Redis @ DotNetToscana
Key-value databases in practice Redis @ DotNetToscana
Matteo Baglini
 
Slide Seminar PHP Indonesia - NoSQL Redis
Slide Seminar PHP Indonesia - NoSQL RedisSlide Seminar PHP Indonesia - NoSQL Redis
Slide Seminar PHP Indonesia - NoSQL Redis
rifqi alfian
 
Redis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHPRedis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHP
Ricard Clau
 
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...
Beyond relational database - Building high performance websites using Redis a...
Dinh Pham
 
Scaling PHP to 40 Million Uniques
Scaling PHP to 40 Million UniquesScaling PHP to 40 Million Uniques
Scaling PHP to 40 Million Uniques
Jonathan Klein
 
PHP with Service BUS (RabbitMQ/Redis/MongoDB) - IMasters PHP Experience 2016
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
Alexandre Brandão Lustosa
 
Redis everywhere - PHP London
Redis everywhere - PHP LondonRedis everywhere - PHP London
Redis everywhere - PHP London
Ricard Clau
 
MOSC2012 - Building High-Performance Web-Application with PHP & MongoDB
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
r1dotmy
 
Key-value databases in practice Redis @ DotNetToscana
Key-value databases in practice Redis @ DotNetToscanaKey-value databases in practice Redis @ DotNetToscana
Key-value databases in practice Redis @ DotNetToscana
Matteo Baglini
 
Slide Seminar PHP Indonesia - NoSQL Redis
Slide Seminar PHP Indonesia - NoSQL RedisSlide Seminar PHP Indonesia - NoSQL Redis
Slide Seminar PHP Indonesia - NoSQL Redis
rifqi alfian
 
Redis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHPRedis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHP
Ricard Clau
 
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...
Beyond relational database - Building high performance websites using Redis a...
Dinh Pham
 
Scaling PHP to 40 Million Uniques
Scaling PHP to 40 Million UniquesScaling PHP to 40 Million Uniques
Scaling PHP to 40 Million Uniques
Jonathan Klein
 
PHP with Service BUS (RabbitMQ/Redis/MongoDB) - IMasters PHP Experience 2016
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
Alexandre Brandão Lustosa
 
Redis everywhere - PHP London
Redis everywhere - PHP LondonRedis everywhere - PHP London
Redis everywhere - PHP London
Ricard Clau
 
Ad

Similar to Redis in Practice: Scenarios, Performance and Practice with PHP (20)

Python redis talk
Python redis talkPython redis talk
Python redis talk
Josiah Carlson
 
quickguide-einnovator-9-redis
quickguide-einnovator-9-redisquickguide-einnovator-9-redis
quickguide-einnovator-9-redis
jorgesimao71
 
深入了解Redis
深入了解Redis深入了解Redis
深入了解Redis
iammutex
 
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
Yandex
 
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander KorotkovPostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
Nikolay Samokhvalov
 
Redis introduction
Redis introductionRedis introduction
Redis introduction
Federico Daniel Colombo Gennarelli
 
No sql solutions - 공개용
No sql solutions - 공개용No sql solutions - 공개용
No sql solutions - 공개용
Byeongweon Moon
 
Introduction to redis
Introduction to redisIntroduction to redis
Introduction to redis
Tanu Siwag
 
DTCC '14 Spark Runtime Internals
DTCC '14 Spark Runtime InternalsDTCC '14 Spark Runtime Internals
DTCC '14 Spark Runtime Internals
Cheng Lian
 
Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...
Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...
Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...
Gruter
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
Itamar Haber
 
Apache Tajo: Query Optimization Techniques and JIT-based Vectorized Engine
Apache Tajo: Query Optimization Techniques and JIT-based Vectorized EngineApache Tajo: Query Optimization Techniques and JIT-based Vectorized Engine
Apache Tajo: Query Optimization Techniques and JIT-based Vectorized Engine
DataWorks Summit
 
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
javier ramirez
 
Redis
RedisRedis
Redis
Rajesh Kumar
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Data Con LA
 
Scaling Web Applications with Cassandra Presentation.ppt
Scaling Web Applications with Cassandra Presentation.pptScaling Web Applications with Cassandra Presentation.ppt
Scaling Web Applications with Cassandra Presentation.ppt
ssuserbad56d
 
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Ontico
 
Cassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A ComparisonCassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A Comparison
shsedghi
 
Redis Modules - Redis India Tour - 2017
Redis Modules - Redis India Tour - 2017Redis Modules - Redis India Tour - 2017
Redis Modules - Redis India Tour - 2017
HashedIn Technologies
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014
Michael Renner
 
quickguide-einnovator-9-redis
quickguide-einnovator-9-redisquickguide-einnovator-9-redis
quickguide-einnovator-9-redis
jorgesimao71
 
深入了解Redis
深入了解Redis深入了解Redis
深入了解Redis
iammutex
 
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
Yandex
 
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander KorotkovPostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
Nikolay Samokhvalov
 
No sql solutions - 공개용
No sql solutions - 공개용No sql solutions - 공개용
No sql solutions - 공개용
Byeongweon Moon
 
Introduction to redis
Introduction to redisIntroduction to redis
Introduction to redis
Tanu Siwag
 
DTCC '14 Spark Runtime Internals
DTCC '14 Spark Runtime InternalsDTCC '14 Spark Runtime Internals
DTCC '14 Spark Runtime Internals
Cheng Lian
 
Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...
Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...
Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...
Gruter
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
Itamar Haber
 
Apache Tajo: Query Optimization Techniques and JIT-based Vectorized Engine
Apache Tajo: Query Optimization Techniques and JIT-based Vectorized EngineApache Tajo: Query Optimization Techniques and JIT-based Vectorized Engine
Apache Tajo: Query Optimization Techniques and JIT-based Vectorized Engine
DataWorks Summit
 
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
javier ramirez
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Data Con LA
 
Scaling Web Applications with Cassandra Presentation.ppt
Scaling Web Applications with Cassandra Presentation.pptScaling Web Applications with Cassandra Presentation.ppt
Scaling Web Applications with Cassandra Presentation.ppt
ssuserbad56d
 
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Ontico
 
Cassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A ComparisonCassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A Comparison
shsedghi
 
Redis Modules - Redis India Tour - 2017
Redis Modules - Redis India Tour - 2017Redis Modules - Redis India Tour - 2017
Redis Modules - Redis India Tour - 2017
HashedIn Technologies
 
Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014Postgres Vienna DB Meetup 2014
Postgres Vienna DB Meetup 2014
Michael Renner
 
Ad

Recently uploaded (19)

IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 

Redis in Practice: Scenarios, Performance and Practice with PHP

  • 1. Redis in Practice • Why Redis • How to make Redis Faster • Replication and Sentinel Chen Huang c.huang@*****.com
  • 2. Content • Why Redis  Comparison of In-Memory Storages  Scenarios  Sharding (Parallel Scaling) • How to make Redis Faster • Replication and Sentinel
  • 3. Comparison of In-Memory Storages Redis Memcached MemSQL Data Structure Key-Value, List, Hash, Set, Z-Set Key-Value Relational Concurrency Poor Good Good Sharding Not Generally Available Yes Yes Transaction Optimistic Lock CAS No Scripting Lua No No Replication Yes Repcached Yes Persistance Yes MemcacheDB Yes High Availability Redis Sentinel ? ?
  • 4. Scenarios • Cache Java: Map cache = new LinkedHashMap() { protected boolean removeEldestEntry(Map.Entry eldest) { return isTimeout(eldest); } } Redis: SETEX key timeout value
  • 5. Scenarios • List / Queue Java Redis LinkedList / ArrayDeque List list.offerFirst(element) LPUSH list element list.offerLast(element) RPUSH list element list.pollFirst() LPOP list list.pollLast() RPOP list
  • 6. • Session [Servlet API] HttpSession session = req.getSession(); // got by session id Object oldValue = session.getAttribute(key); session.setAttribute(key, newValue); [Implementation] Scenarios Java Redis HashMap<String, HashMap> Hash map.get(id).get(key); HGET id key map.get(id).put(key, value); HSET id key value
  • 7. Scenarios • Session Timeout [Servlet API] session.set(key, new HttpSessionBindingListener() { public void valueUnbound(HttpSessionBindingEvent event) { // Trigger Timeout Event } }); [Implementation] Java Redis LinkedHashMap Hash + Sorted Set (ZSet) Iterator i = map.values().iterator(); while (i.hasNext() && isTimeout(i.next())) { // Trigger Timeout Event i.remove(); } ZRANGEBYSCORE zset 0 now // Trigger Timeout Event HDEL id, id, ... ZREMRANGEBYSCORE zset 0 now
  • 8. Sharding (Parallel Scaling) • Redis is Single-Threaded • Multiple Redis Instances in one Server • Partition by Hash of Keys
  • 9. Content • Why Redis • How to make Redis Faster  Time Complexity  Communication Latency  Serialization • Replication and Sentinel
  • 10. Time Complexity See Redis Documentation for more Details Structure Operation Complexity Hash HGET id key Key-Value GET id Key-Value KEYS prefix* List LPUSH/LPOP List LINDEX/LSET Sorted Set ZADD Sorted Set ZRANGEBYSCORE O(1) O(1) O(n) O(1) O(n) O(log(n)) O(log(n) +m)
  • 11. Communication Latency • Massive (Multi-Row) Insertion [SQL] × INSERT INTO cache (key, value) VALUES ("key1", "value1"); INSERT INTO cache (key, value) VALUES ("key2", "value2"); ... √ INSERT INTO cache (key, value) VALUES ("key1", "value1"), ("key2", "value2"), ("key3", "value3"), ... [Redis] × HSET cache key1 value1 HSET cache key2 value2 ... √ HMSET cache key1 value1 key2 value2 ...
  • 13. Communication Latency • Pipeline (Batch) [SQL in Java] try (Statement stmt = conn.createStatement()) { stmt.addBatch("INSERT INTO cache1 ..."); stmt.addBatch("INSERT INTO cache2 ..."); stmt.executeBatch(); } [Redis in Java] Pipeline pl = jedis.pipelined(); pl.hset("cache1", "key1", "value1"); pl.hset("cache2", "key2", "value2"); pl.sync();
  • 14. Communication Latency • Scripting [Java] int balance = Integer.parseInt(jedis.get("balance")); if (balance > 100) { jedis.set("balance", Integer.toString(balance - 100)); } [Lua] local i = tonumber(redis.call('get', 'balance')) if i > 100 then redis.call('set', 'balance', tostring(i - 100)) end
  • 15. Communication Latency • SQL Efficiency Multi-Row Insertion > Batch > Stored Procedure • Redis Efficiency Massive Insertion > Pipeline > Scripting
  • 19. Content • Why Redis • How to make Redis Faster • Replication and Sentinel  Replication  Sentinel  Practice with PHP
  • 22. Practice with PHP Shard 1 Shard 2 Sentinels Shard 3 Shard 4 Web Server Config Center Write Read Scheduled Config Sync Web Server Web Server redis.config.php redis.config.php redis.config.php redis.config.php Scheduled Config Sync