SlideShare une entreprise Scribd logo
1  sur  57
Redis in Practice
NoSQL NYC • December 2nd, 2010
    Noah Davis & Luke Melia
About Noah & Luke

Weplay.com
Rubyists
Running Redis in production since mid-2009
@noahd1 and @lukemelia on Twitter
Pronouncing Redis
Tonight’s gameplan
Fly-by intro to Redis
Redis in Practice
   View counts                     Q&A
                           throughout, please.
   Global locks               We love being
   Presence                    interrupted.

   Social activity feeds
   Friend suggestions
   Caching
Salvatore
     Sanfilippo
 Original author of Redis.
   @antirez on Twitter.
       Lives in Italy.
Recently hired by VMWare.
  Great project leader.
Describing Redis

Remote dictionary server
“advanced, fast, persistent key- value database”
“Data structures server”
“memcached on steroids”
In Salvatore’s words

 “I see Redis definitely more as a flexible tool
than as a solution specialized to solve a specific
  problem: his mixed soul of cache, store, and
    messaging server shows this very well.”
             - Salvatore Sanfilippo
Qualities
Written in C
Few dependencies
Fast
Single-threaded
Lots of clients available
Initial release was March 2009
Features
Key-value store where a value is one of:
   scalar/string, list, set, sorted sets, hash
Persistence: in-memory, snapshots, append-only log, VM
Replication: master-slave, configureable
Pub-Sub
Expiry
“Transaction”-y
In development: Redis Cluster
What Redis ain’t (...yet)

Big data
Seamless scaling
Ad-hoc query tool
The only data store you’ll ever need
Who’s using Redis?
VMWare
                 Grooveshark
Github
                 Superfeedr
Craigslist
                 Ravelry
EngineYard
                 mediaFAIL
The Guardian
                 Weplay
Forrst
                 More...
PostRank
Our infrastructure
App server           App server   Utility server




      MySQL master                   Redis master




       MySQL slave                   Redis slave
Redis in Practice #1

View Counts
View counts

potential for massive amounts of simple writes/reads
valuable data, but not mission critical
lots of row contention in SQL
Redis incrementing
    $ redis-cli
    redis> incr "medium:301:views"
    (integer) 1
    redis> incr "medium:301:views"
    (integer) 2
    redis> incrby "medium:301:views" 5
    (integer) 7
    redis> decr "medium:301:views"
    (integer) 6
Redis in Practice #2

Distributed Locks
Subscribe to a Weplay Calendar




                        Subscribe to “ics”
Subscription challenges


Generally static content for long periods of time, but with
short sessions of frequent updates
Expensive to compute on the fly
Without Redis/Locking
     CANCEL EVENT                 BACKGROUND                  Pubisher
                                     QUEUE


                Queue: Publish ICS



                                                  Publish




                                                                     Contention/Redundancy


       ADD EVENT                     BACKGROUND                Pubisher
                                        QUEUE


                    Queue: Publish ICS



                                                    Publish
Redis Locking: SetNX
  redis = Redis.new
  redis.setnx "locking.key", Time.now + 2.hours
  => true
  redis.setnx "locking.key", Time.now + 2.hours
  => false
  redis.del "locking.key"
  => true¨
  redis.setnx "locking.key", Time.now + 2.hours
  => true
Redis: Obtained Lock
ADD EVENT                                  REDIS




            SETNX "group_34_publish_ics"



                   Returns: 1




                                       BACKGROUND                              PUBLISHER                       REDIS
                                          QUEUE




                                                    5 minutes later: PUBLISH....
        Queue Job: Publish.publish_ics("34")
                                                                                      DEL "group_34_publish_ics"
Redis: Locked Out
   CANCEL EVENT                                                  REDIS




                         SETNX "group_34_publish_ics"

                                Returns: 0




                  ADD EVENT                                              REDIS




                                       SETNX "group_34_publish_ics"

                                              Returns: 0
Redis in Practice #3

 Presence
“Who’s online?”
Weplay members told us
they wanted to be able
to see which of their
friends were online...
About sets
0 to N elements       Adding a value to a set
                      does not require you
Unordered
                      to check if the value
No repeated members   exists in the set first
Working with Redis sets 1/3
# SADD key, member
# Adds the specified member to the set stored at key

redis = Redis.new
redis.sadd 'my_set', 'foo'   #   =>   true
redis.sadd 'my_set', 'bar'   #   =>   true
redis.sadd 'my_set', 'bar'   #   =>   false
redis.smembers 'my_set'      #   =>   ["foo", "bar"]
Working with Redis sets 2/3
# SUNION key1 key2 ... keyN
# Returns the members of a set resulting from the union of all
# the sets stored at the specified keys.

# SUNIONSTORE <i>dstkey key1 key2 ... keyN</i></b>
# Works like SUNION but instead of being returned the resulting
# set is stored as dstkey.

redis = Redis.new
redis.sadd 'set_a', 'foo'
redis.sadd 'set_a', 'bar'
redis.sadd 'set_b', 'bar'
redis.sadd 'set_b', 'baz'
redis.sunion 'set_a', 'set_b'        # => ["foo", "baz", "bar"]

redis.sunionstore 'set_ab', 'set_a', 'set_b'
redis.smembers 'set_ab'              # => ["foo", "baz", "bar"]
Working with Redis sets 3/3
# SINTER key1 key2 ... keyN
# Returns the members that are present in all
# sets stored at the specified keys.

redis = Redis.new
redis.sadd 'set_a', 'foo'
redis.sadd 'set_a', 'bar'
redis.sadd 'set_b', 'bar'
redis.sadd 'set_b', 'baz'
redis.sinter 'set_a', 'set_b'      # => ["bar"]
Approach 1/2
Approach 2/2
Implementation 1/2
# Defining the keys

def current_key
  key(Time.now.strftime("%M"))
end

def keys_in_last_5_minutes
  now = Time.now
  times = (0..5).collect {|n| now - n.minutes }
  times.collect{ |t| key(t.strftime("%M")) }
end

def key(minute)
  "online_users_minute_#{minute}"
end
Implementation 2/2
# Tracking an Active User, and calculating who’s online

def track_user_id(id)
  key = current_key
  redis.sadd(key, id)
end

def online_user_ids
  redis.sunion(*keys_in_last_5_minutes)
end

def online_friend_ids(interested_user_id)
  redis.sunionstore("online_users", *keys_in_last_5_minutes)
  redis.sinter("online_users",
               "user:#{interested_user_id}:friend_ids")
end
Redis in Practice #4

Social Activity Feeds
Social Activity Feeds
Via SQL, Approach 1/2
 Doesn’t scale to more
 complex social graphs
 e.g. friends who are         SELECT activities.*
                                FROM activities
                                JOIN friendships f1 ON f1.from_id =
 ‘hidden’ from your feed      activities.actor_id
                                JOIN friendships f2 ON f2.to_id   =
                              activities.actor_id
 May still require multiple     WHERE f1.to_id = ? OR f2.from_id = ?
                               ORDER BY activities.id DESC

 queries to grab               LIMIT 15



 unindexed data
Via SQL, Approach 2/2                             user_id



                                                   11
                                                            activity_id



                                                               96

                                                   22          96

                                                   11          97

                                                   22          97

                                                   33          97

                                                   11          98

                                                   22          98

                          Friend: 11               11          99

    Activity: 100
                                                   11        100
               Actor 1    Friend: 22
                                        INSERTS
                                                   22        100
                         Teammate: 33
                                                   33        100
Large SQL table

Grew quickly
Difficult to maintain
Difficult to prune
Redis Lists 1/2
      redis> lpush "teams" "yankees"
      (integer) 1
      redis> lpush "teams" "redsox"
      (integer) 2
      redis> llen "teams"
      (integer) 2
      redis> lrange "teams" 0 1
      1. "redsox"
      2. "yankees"
      redis> lrange "teams" 0 -1
      1. "redsox"
      2. "yankees"
                                       LTRIM, LLEN, LRANGE
Redis Lists 2/2
      redis> ltrim "teams" 0 0
      OK
      redis> lrange "teams" 0 -1
      1. "redsox"




                                   LTRIM
via Redis, 1/2
                            LPUSH “user:11:feed”, “100”
                            LTRIM “user:11:feed”, 0, 50
                                     LPUSH 'user:11:feed', '100'        Key             Value
                      Friend: 11
                                     LTRIM 'user:11:feed', 0, 50

Activity: 100
                                                                    user:11:feed   [100,99,97,96]
                                     LPUSH 'user:22:feed', '100'
           Actor 1    Friend: 22
                                     LTRIM 'user:22:feed', 0, 50
                                                                    user:22:feed    [100,99,98]

                                     LPUSH 'user:33:feed', '100'
                     Teammate: 33
                                     LTRIM 'user:33:feed', 0, 100   user:33:feed      [100,99]
via Redis, 2/2
                                          Key             Value
                       Friend: 11


                                      user:11:feed   [100,99,97,96]

                       Friend: 22
                                     user:22:feed     [100,99,98]
 Activity: 100


            Actor 1
                                     user:33:feed       [100,99]
                      Teammate: 33




                                          Key             Value

                       New York
                                     new_york:feed      [100,67]


                         Boston       boston:feed       [100,99]
Rendering the Feed
Redis in Practice #5

Friend Suggestions
Friend Suggestions

suggest new connections based on
existing connections
expanding the social graph and
mirroring real world connections is key
The Concept

            Paul




Me         George   John




            Ringo
The Yoko Factor

            Paul




Me         George      John   Yoko




            Ringo
The Approach 1/2
           Sarah




                       2

           Frank           Donny




     Me            2

             Ted

                            Erika
The Approach 2/2
           Sarah




                   2

           Frank       Donny




     Me



             Ted
                   3
                        Erika




            Sue
ZSETS in Redis

“Sorted Sets”
Each member of the set has a score
Ordered by the score at all times
Friend Suggestions in Redis
zincrby “user:1:suggestions” 1 “donny”
zincrby “user:1:suggestions” 1 “donny”
                                          Sarah




                                          Frank   Donny




                                     Me




zincrby “user:1:suggestions” 1 “erika”
                                            Ted

                                                   Erika


zincrby “user:1:suggestions” 1 “erika”

     [ Donny   2   , Erika   2   ]
Friend Suggestions in Redis
zincrby “user:1:suggestions” 1 “erika”
                                          Sarah




                                          Frank   Donny




                                     Me



                                            Ted



zrevrange “user:1:suggestions” 0 1                 Erika




                                           Sue




     [ Erika   3   , Donny   2   ]
Redis in Practice #6

  Caching
Suitability for caching
Excellent match for managed denormalization
   ex. friendships, teams, teammates
Excellent match where you would benefit from persistence
and/or replication
Historically, not a good match for a “generational cache,” in
which you want to optimize memory use by evicting least-
recently used (LRU) keys
As an LRU cache
TTL-support since inception, but with unintuitive behavior
   Writing to volatile key replaced it and cleared the TTL
Redis 2.2 changes this behavior and adds key features:
   ability to write to, and update expiry of volatile keys
   maxmemory [bytes], maxmemory-policy [policy]
   policies: volatile-lru, volatile-ttl, volatile-random,
   allkeys-lru, allkeys-random
Easy to adapt



Namespaced Rack::Session, Rack::Cache, I18n and cache
Redis cache stores for Ruby web frameworks
   implementation is under 1,000 LOC
Contentious benchmarks
Any
questions?




                  Thanks!
    Follow us on Twitter: @noahd1 and @lukemelia
   Tell your friends in youth sports about Weplay.com

Contenu connexe

Tendances

An Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL databaseAn Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL databaseAli MasudianPour
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query OptimizationMongoDB
 
RocksDB compaction
RocksDB compactionRocksDB compaction
RocksDB compactionMIJIN AN
 
When to Use MongoDB
When to Use MongoDBWhen to Use MongoDB
When to Use MongoDBMongoDB
 
Redis Introduction
Redis IntroductionRedis Introduction
Redis IntroductionAlex Su
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMike Dirolf
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redisDvir Volk
 
An Introduction to Redis for Developers.pdf
An Introduction to Redis for Developers.pdfAn Introduction to Redis for Developers.pdf
An Introduction to Redis for Developers.pdfStephen Lorello
 
Redis overview for Software Architecture Forum
Redis overview for Software Architecture ForumRedis overview for Software Architecture Forum
Redis overview for Software Architecture ForumChristopher Spring
 
Common MongoDB Use Cases
Common MongoDB Use Cases Common MongoDB Use Cases
Common MongoDB Use Cases MongoDB
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use CasesFabrizio Farinacci
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDBMongoDB
 
Zookeeper Introduce
Zookeeper IntroduceZookeeper Introduce
Zookeeper Introducejhao niu
 
Paris Redis Meetup Introduction
Paris Redis Meetup IntroductionParis Redis Meetup Introduction
Paris Redis Meetup IntroductionGregory Boissinot
 
Everything you always wanted to know about Redis but were afraid to ask
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
 
Using ClickHouse for Experimentation
Using ClickHouse for ExperimentationUsing ClickHouse for Experimentation
Using ClickHouse for ExperimentationGleb Kanterov
 
Inside the InfluxDB storage engine
Inside the InfluxDB storage engineInside the InfluxDB storage engine
Inside the InfluxDB storage engineInfluxData
 
Bucket your partitions wisely - Cassandra summit 2016
Bucket your partitions wisely - Cassandra summit 2016Bucket your partitions wisely - Cassandra summit 2016
Bucket your partitions wisely - Cassandra summit 2016Markus Höfer
 

Tendances (20)

An Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL databaseAn Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL database
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 
RocksDB compaction
RocksDB compactionRocksDB compaction
RocksDB compaction
 
When to Use MongoDB
When to Use MongoDBWhen to Use MongoDB
When to Use MongoDB
 
redis basics
redis basicsredis basics
redis basics
 
Redis Introduction
Redis IntroductionRedis Introduction
Redis Introduction
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
 
An Introduction to Redis for Developers.pdf
An Introduction to Redis for Developers.pdfAn Introduction to Redis for Developers.pdf
An Introduction to Redis for Developers.pdf
 
Redis overview for Software Architecture Forum
Redis overview for Software Architecture ForumRedis overview for Software Architecture Forum
Redis overview for Software Architecture Forum
 
Common MongoDB Use Cases
Common MongoDB Use Cases Common MongoDB Use Cases
Common MongoDB Use Cases
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use Cases
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
 
Zookeeper Introduce
Zookeeper IntroduceZookeeper Introduce
Zookeeper Introduce
 
Paris Redis Meetup Introduction
Paris Redis Meetup IntroductionParis Redis Meetup Introduction
Paris Redis Meetup Introduction
 
Everything you always wanted to know about Redis but were afraid to ask
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 ask
 
Using ClickHouse for Experimentation
Using ClickHouse for ExperimentationUsing ClickHouse for Experimentation
Using ClickHouse for Experimentation
 
Inside the InfluxDB storage engine
Inside the InfluxDB storage engineInside the InfluxDB storage engine
Inside the InfluxDB storage engine
 
Bucket your partitions wisely - Cassandra summit 2016
Bucket your partitions wisely - Cassandra summit 2016Bucket your partitions wisely - Cassandra summit 2016
Bucket your partitions wisely - Cassandra summit 2016
 

Similaire à Redis in Practice

REDIS intro and how to use redis
REDIS intro and how to use redisREDIS intro and how to use redis
REDIS intro and how to use redisKris Jeong
 
Reinforcement Learning On Hundreds Of Thousands Of Cores: Henrique Pondedeoli...
Reinforcement Learning On Hundreds Of Thousands Of Cores: Henrique Pondedeoli...Reinforcement Learning On Hundreds Of Thousands Of Cores: Henrique Pondedeoli...
Reinforcement Learning On Hundreds Of Thousands Of Cores: Henrique Pondedeoli...Redis Labs
 
Indexing thousands of writes per second with redis
Indexing thousands of writes per second with redisIndexing thousands of writes per second with redis
Indexing thousands of writes per second with redispauldix
 
10 Ways to Scale with Redis - LA Redis Meetup 2019
10 Ways to Scale with Redis - LA Redis Meetup 201910 Ways to Scale with Redis - LA Redis Meetup 2019
10 Ways to Scale with Redis - LA Redis Meetup 2019Dave Nielsen
 
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 DatabasesKarel Minarik
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
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, HerokuRedis Labs
 
10 Ways to Scale Your Website Silicon Valley Code Camp 2019
10 Ways to Scale Your Website Silicon Valley Code Camp 201910 Ways to Scale Your Website Silicon Valley Code Camp 2019
10 Ways to Scale Your Website Silicon Valley Code Camp 2019Dave Nielsen
 
Amir Salihefendic: Redis - the hacker's database
Amir Salihefendic: Redis - the hacker's databaseAmir Salihefendic: Redis - the hacker's database
Amir Salihefendic: Redis - the hacker's databaseit-people
 
Extend Redis with Modules
Extend Redis with ModulesExtend Redis with Modules
Extend Redis with ModulesItamar Haber
 
WebClusters, Redis
WebClusters, RedisWebClusters, Redis
WebClusters, RedisFilip Tepper
 
Advanced Redis data structures
Advanced Redis data structuresAdvanced Redis data structures
Advanced Redis data structuresamix3k
 
Patterns for key-value stores
Patterns for key-value storesPatterns for key-value stores
Patterns for key-value storesOle-Martin Mørk
 
Drupalcamp gent - Node access
Drupalcamp gent - Node accessDrupalcamp gent - Node access
Drupalcamp gent - Node accessJasper Knops
 
Service Discovery & Load-Balancing under Docker 1.12.0 @ Docker Meetup #22
Service Discovery & Load-Balancing under Docker 1.12.0 @ Docker Meetup #22Service Discovery & Load-Balancing under Docker 1.12.0 @ Docker Meetup #22
Service Discovery & Load-Balancing under Docker 1.12.0 @ Docker Meetup #22Ajeet Singh Raina
 
Redis学习笔记
Redis学习笔记Redis学习笔记
Redis学习笔记yongboy
 
Redis SoCraTes 2014
Redis SoCraTes 2014Redis SoCraTes 2014
Redis SoCraTes 2014steffenbauer
 
Redispresentation apac2012
Redispresentation apac2012Redispresentation apac2012
Redispresentation apac2012Ankur Gupta
 

Similaire à Redis in Practice (20)

REDIS intro and how to use redis
REDIS intro and how to use redisREDIS intro and how to use redis
REDIS intro and how to use redis
 
Reinforcement Learning On Hundreds Of Thousands Of Cores: Henrique Pondedeoli...
Reinforcement Learning On Hundreds Of Thousands Of Cores: Henrique Pondedeoli...Reinforcement Learning On Hundreds Of Thousands Of Cores: Henrique Pondedeoli...
Reinforcement Learning On Hundreds Of Thousands Of Cores: Henrique Pondedeoli...
 
Indexing thousands of writes per second with redis
Indexing thousands of writes per second with redisIndexing thousands of writes per second with redis
Indexing thousands of writes per second with redis
 
10 Ways to Scale with Redis - LA Redis Meetup 2019
10 Ways to Scale with Redis - LA Redis Meetup 201910 Ways to Scale with Redis - LA Redis Meetup 2019
10 Ways to Scale with Redis - LA Redis Meetup 2019
 
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
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
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
 
10 Ways to Scale Your Website Silicon Valley Code Camp 2019
10 Ways to Scale Your Website Silicon Valley Code Camp 201910 Ways to Scale Your Website Silicon Valley Code Camp 2019
10 Ways to Scale Your Website Silicon Valley Code Camp 2019
 
Amir Salihefendic: Redis - the hacker's database
Amir Salihefendic: Redis - the hacker's databaseAmir Salihefendic: Redis - the hacker's database
Amir Salihefendic: Redis - the hacker's database
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
 
Redis
RedisRedis
Redis
 
Extend Redis with Modules
Extend Redis with ModulesExtend Redis with Modules
Extend Redis with Modules
 
WebClusters, Redis
WebClusters, RedisWebClusters, Redis
WebClusters, Redis
 
Advanced Redis data structures
Advanced Redis data structuresAdvanced Redis data structures
Advanced Redis data structures
 
Patterns for key-value stores
Patterns for key-value storesPatterns for key-value stores
Patterns for key-value stores
 
Drupalcamp gent - Node access
Drupalcamp gent - Node accessDrupalcamp gent - Node access
Drupalcamp gent - Node access
 
Redis
RedisRedis
Redis
 
Service Discovery & Load-Balancing under Docker 1.12.0 @ Docker Meetup #22
Service Discovery & Load-Balancing under Docker 1.12.0 @ Docker Meetup #22Service Discovery & Load-Balancing under Docker 1.12.0 @ Docker Meetup #22
Service Discovery & Load-Balancing under Docker 1.12.0 @ Docker Meetup #22
 
Redis学习笔记
Redis学习笔记Redis学习笔记
Redis学习笔记
 
Redis SoCraTes 2014
Redis SoCraTes 2014Redis SoCraTes 2014
Redis SoCraTes 2014
 
Redispresentation apac2012
Redispresentation apac2012Redispresentation apac2012
Redispresentation apac2012
 

Dernier

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Dernier (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

Redis in Practice

  • 1. Redis in Practice NoSQL NYC • December 2nd, 2010 Noah Davis & Luke Melia
  • 2. About Noah & Luke Weplay.com Rubyists Running Redis in production since mid-2009 @noahd1 and @lukemelia on Twitter
  • 4. Tonight’s gameplan Fly-by intro to Redis Redis in Practice View counts Q&A throughout, please. Global locks We love being Presence interrupted. Social activity feeds Friend suggestions Caching
  • 5. Salvatore Sanfilippo Original author of Redis. @antirez on Twitter. Lives in Italy. Recently hired by VMWare. Great project leader.
  • 6. Describing Redis Remote dictionary server “advanced, fast, persistent key- value database” “Data structures server” “memcached on steroids”
  • 7. In Salvatore’s words “I see Redis definitely more as a flexible tool than as a solution specialized to solve a specific problem: his mixed soul of cache, store, and messaging server shows this very well.” - Salvatore Sanfilippo
  • 8. Qualities Written in C Few dependencies Fast Single-threaded Lots of clients available Initial release was March 2009
  • 9. Features Key-value store where a value is one of: scalar/string, list, set, sorted sets, hash Persistence: in-memory, snapshots, append-only log, VM Replication: master-slave, configureable Pub-Sub Expiry “Transaction”-y In development: Redis Cluster
  • 10. What Redis ain’t (...yet) Big data Seamless scaling Ad-hoc query tool The only data store you’ll ever need
  • 11. Who’s using Redis? VMWare Grooveshark Github Superfeedr Craigslist Ravelry EngineYard mediaFAIL The Guardian Weplay Forrst More... PostRank
  • 12. Our infrastructure App server App server Utility server MySQL master Redis master MySQL slave Redis slave
  • 13. Redis in Practice #1 View Counts
  • 14. View counts potential for massive amounts of simple writes/reads valuable data, but not mission critical lots of row contention in SQL
  • 15. Redis incrementing $ redis-cli redis> incr "medium:301:views" (integer) 1 redis> incr "medium:301:views" (integer) 2 redis> incrby "medium:301:views" 5 (integer) 7 redis> decr "medium:301:views" (integer) 6
  • 16. Redis in Practice #2 Distributed Locks
  • 17. Subscribe to a Weplay Calendar Subscribe to “ics”
  • 18. Subscription challenges Generally static content for long periods of time, but with short sessions of frequent updates Expensive to compute on the fly
  • 19. Without Redis/Locking CANCEL EVENT BACKGROUND Pubisher QUEUE Queue: Publish ICS Publish Contention/Redundancy ADD EVENT BACKGROUND Pubisher QUEUE Queue: Publish ICS Publish
  • 20. Redis Locking: SetNX redis = Redis.new redis.setnx "locking.key", Time.now + 2.hours => true redis.setnx "locking.key", Time.now + 2.hours => false redis.del "locking.key" => true¨ redis.setnx "locking.key", Time.now + 2.hours => true
  • 21. Redis: Obtained Lock ADD EVENT REDIS SETNX "group_34_publish_ics" Returns: 1 BACKGROUND PUBLISHER REDIS QUEUE 5 minutes later: PUBLISH.... Queue Job: Publish.publish_ics("34") DEL "group_34_publish_ics"
  • 22. Redis: Locked Out CANCEL EVENT REDIS SETNX "group_34_publish_ics" Returns: 0 ADD EVENT REDIS SETNX "group_34_publish_ics" Returns: 0
  • 23. Redis in Practice #3 Presence
  • 24. “Who’s online?” Weplay members told us they wanted to be able to see which of their friends were online...
  • 25. About sets 0 to N elements Adding a value to a set does not require you Unordered to check if the value No repeated members exists in the set first
  • 26. Working with Redis sets 1/3 # SADD key, member # Adds the specified member to the set stored at key redis = Redis.new redis.sadd 'my_set', 'foo' # => true redis.sadd 'my_set', 'bar' # => true redis.sadd 'my_set', 'bar' # => false redis.smembers 'my_set' # => ["foo", "bar"]
  • 27. Working with Redis sets 2/3 # SUNION key1 key2 ... keyN # Returns the members of a set resulting from the union of all # the sets stored at the specified keys. # SUNIONSTORE <i>dstkey key1 key2 ... keyN</i></b> # Works like SUNION but instead of being returned the resulting # set is stored as dstkey. redis = Redis.new redis.sadd 'set_a', 'foo' redis.sadd 'set_a', 'bar' redis.sadd 'set_b', 'bar' redis.sadd 'set_b', 'baz' redis.sunion 'set_a', 'set_b' # => ["foo", "baz", "bar"] redis.sunionstore 'set_ab', 'set_a', 'set_b' redis.smembers 'set_ab' # => ["foo", "baz", "bar"]
  • 28. Working with Redis sets 3/3 # SINTER key1 key2 ... keyN # Returns the members that are present in all # sets stored at the specified keys. redis = Redis.new redis.sadd 'set_a', 'foo' redis.sadd 'set_a', 'bar' redis.sadd 'set_b', 'bar' redis.sadd 'set_b', 'baz' redis.sinter 'set_a', 'set_b' # => ["bar"]
  • 31. Implementation 1/2 # Defining the keys def current_key   key(Time.now.strftime("%M")) end def keys_in_last_5_minutes   now = Time.now   times = (0..5).collect {|n| now - n.minutes }   times.collect{ |t| key(t.strftime("%M")) } end def key(minute)   "online_users_minute_#{minute}" end
  • 32. Implementation 2/2 # Tracking an Active User, and calculating who’s online def track_user_id(id)   key = current_key   redis.sadd(key, id) end def online_user_ids   redis.sunion(*keys_in_last_5_minutes) end def online_friend_ids(interested_user_id)   redis.sunionstore("online_users", *keys_in_last_5_minutes)   redis.sinter("online_users", "user:#{interested_user_id}:friend_ids") end
  • 33. Redis in Practice #4 Social Activity Feeds
  • 35. Via SQL, Approach 1/2 Doesn’t scale to more complex social graphs e.g. friends who are SELECT activities.* FROM activities JOIN friendships f1 ON f1.from_id = ‘hidden’ from your feed activities.actor_id JOIN friendships f2 ON f2.to_id = activities.actor_id May still require multiple WHERE f1.to_id = ? OR f2.from_id = ? ORDER BY activities.id DESC queries to grab LIMIT 15 unindexed data
  • 36. Via SQL, Approach 2/2 user_id 11 activity_id 96 22 96 11 97 22 97 33 97 11 98 22 98 Friend: 11 11 99 Activity: 100 11 100 Actor 1 Friend: 22 INSERTS 22 100 Teammate: 33 33 100
  • 37. Large SQL table Grew quickly Difficult to maintain Difficult to prune
  • 38. Redis Lists 1/2 redis> lpush "teams" "yankees" (integer) 1 redis> lpush "teams" "redsox" (integer) 2 redis> llen "teams" (integer) 2 redis> lrange "teams" 0 1 1. "redsox" 2. "yankees" redis> lrange "teams" 0 -1 1. "redsox" 2. "yankees" LTRIM, LLEN, LRANGE
  • 39. Redis Lists 2/2 redis> ltrim "teams" 0 0 OK redis> lrange "teams" 0 -1 1. "redsox" LTRIM
  • 40. via Redis, 1/2 LPUSH “user:11:feed”, “100” LTRIM “user:11:feed”, 0, 50 LPUSH 'user:11:feed', '100' Key Value Friend: 11 LTRIM 'user:11:feed', 0, 50 Activity: 100 user:11:feed [100,99,97,96] LPUSH 'user:22:feed', '100' Actor 1 Friend: 22 LTRIM 'user:22:feed', 0, 50 user:22:feed [100,99,98] LPUSH 'user:33:feed', '100' Teammate: 33 LTRIM 'user:33:feed', 0, 100 user:33:feed [100,99]
  • 41. via Redis, 2/2 Key Value Friend: 11 user:11:feed [100,99,97,96] Friend: 22 user:22:feed [100,99,98] Activity: 100 Actor 1 user:33:feed [100,99] Teammate: 33 Key Value New York new_york:feed [100,67] Boston boston:feed [100,99]
  • 43. Redis in Practice #5 Friend Suggestions
  • 44. Friend Suggestions suggest new connections based on existing connections expanding the social graph and mirroring real world connections is key
  • 45. The Concept Paul Me George John Ringo
  • 46. The Yoko Factor Paul Me George John Yoko Ringo
  • 47. The Approach 1/2 Sarah 2 Frank Donny Me 2 Ted Erika
  • 48. The Approach 2/2 Sarah 2 Frank Donny Me Ted 3 Erika Sue
  • 49. ZSETS in Redis “Sorted Sets” Each member of the set has a score Ordered by the score at all times
  • 50. Friend Suggestions in Redis zincrby “user:1:suggestions” 1 “donny” zincrby “user:1:suggestions” 1 “donny” Sarah Frank Donny Me zincrby “user:1:suggestions” 1 “erika” Ted Erika zincrby “user:1:suggestions” 1 “erika” [ Donny 2 , Erika 2 ]
  • 51. Friend Suggestions in Redis zincrby “user:1:suggestions” 1 “erika” Sarah Frank Donny Me Ted zrevrange “user:1:suggestions” 0 1 Erika Sue [ Erika 3 , Donny 2 ]
  • 52. Redis in Practice #6 Caching
  • 53. Suitability for caching Excellent match for managed denormalization ex. friendships, teams, teammates Excellent match where you would benefit from persistence and/or replication Historically, not a good match for a “generational cache,” in which you want to optimize memory use by evicting least- recently used (LRU) keys
  • 54. As an LRU cache TTL-support since inception, but with unintuitive behavior Writing to volatile key replaced it and cleared the TTL Redis 2.2 changes this behavior and adds key features: ability to write to, and update expiry of volatile keys maxmemory [bytes], maxmemory-policy [policy] policies: volatile-lru, volatile-ttl, volatile-random, allkeys-lru, allkeys-random
  • 55. Easy to adapt Namespaced Rack::Session, Rack::Cache, I18n and cache Redis cache stores for Ruby web frameworks implementation is under 1,000 LOC
  • 57. Any questions? Thanks! Follow us on Twitter: @noahd1 and @lukemelia Tell your friends in youth sports about Weplay.com

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \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
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. http://antirez.com/m/p.php?i=220\nvolatile-lru remove a key among the ones with an expire set, trying to remove keys not recently used.\nvolatile-ttl remove a key among the ones with an expire set, trying to remove keys with short remaining time to live.\nvolatile-random remove a random key among the ones with an expire set.\nallkeys-lru like volatile-lru, but will remove every kind of key, both normal keys or keys with an expire set.\nallkeys-random like volatile-random, but will remove every kind of keys, both normal keys and keys with an expire set.\n\n
  55. Another 1500 LOC for specs\n
  56. \n
  57. \n