SlideShare a Scribd company logo
Get more than a cache back!
The Microsoft Azure (Redis) Cache
Maarten Balliauw
@maartenballiauw
Who am I?
Maarten Balliauw
Antwerp, Belgium
Software Engineer, Microsoft
Founder, MyGet
AZUG
Focus on web
ASP.NET MVC, Azure, SignalR, ...
Former MVP Azure & ASPInsider
Big passion: Azure
http://blog.maartenballiauw.be
@maartenballiauw
Shameless self promotion: Pro NuGet -
http://amzn.to/pronuget2
Agenda
Azure Cache
Redis
Data types
Transactions
Pub/sub
Scripting
Sharding/partitioning
Patterns
Azure Cache
Caching on Azure
Windows Server: AppFabric (“Velocity”) (2009-2010)
Azure
(ASP.NET cache)
“Shared Cache” (AppFabric cache, multi-tenant)
Self-Hosted Dedicated Cache
Managed Cache (the above, but managed by Microsoft and with an SLA)
A bit of history...
Caching on Azure
1920: Cache used to be a cache
2012: Cache became the go-to datastore
Twitter stores 800 tweets / timeline in Redis
New application types on Azure: PHP, Node, Java, ...
Too much work to write AppFabric clients for all!
http://www.redis.io/clients
Way easier: just make it work on Windows and Azure
New ways to develop applications
Redis
Redis
“Redis is an open source, BSD licensed,
networked, single-threaded, in-memory key-
value cache and store. It is often referred to as a data
structure server since keys can contain strings, hashes, lists, sets,
sorted sets, bitmaps and hyperloglogs.”
REmote DIctionary Server
Redis
Key-value cache and store (value can be a couple of things)
In-memory (no persistence, but you can)
Single-threaded (atomic operations & transactions)
Networked (it’s a server and it does master/slave)
Some other stuff (scripting, pub/sub, Sentinel, snapshot, …)
Things to remember
So no persistence?
Possible using a lot of I/O
AOF (append-only files)
RDB (Redis DB snapshots)
With or without: all your data must fit in memory
Redis 101
demo
The Little Redis Book
http://openmymind.net/redis.pdf
By Karl Seguin
Data types
Type Example Key Example value
String cache:/home <html><head><title>Home page</title>
Hash categories:1 Field
name
description
numproducts
Member
Books
Books for sale
50000
Set categories:1:products 20 11 56 89 32 4
List products:20:comments [0] -> “...”
[1] -> “...”
[2] -> “...”
Sorted set products:bestsellers Field
Eye Patch
Parrot
Score
84632
82120
+ Bitmap, Hyperloglog
Data types
demo
Data types
Type Example Key Example value
String cache:/home
user:nextid
<html><head><title>Home page</title>
2
Hash user:1 Field
name
handle
Member
Maarten
@maartenballiauw
Set user:1:followers 10 42 99 85
List user:1:timeline [0] -> { ... }
[1] -> { ... }
[2] -> { ... }
Sorted set trending:no:tags Field
#ndcoslo
#redis
Score
84632
82120
+ Bitmap, Hyperloglog
Keys
Good practice: use a pattern for keys
E.g. users:1:maarten
Get by id:
KEYS users:1:*
GET ......
Get by name:
KEYS users:*:maarten
GET ......
O(N) operation – use with caution!
But... .NET?
Lots of options! http://www.redis.io/clients
NuGet:
ServiceStack.Redis
StackExchange.Redis
RedisAspNetProviders
...
Connecting to Redis
from .NET
demo
But... Azure?
“It’s just Redis!”
Main differences: auth mechanism and SSL support
Use local for development from GitHub or NuGet
(Redis-32 or Redis-64)
Azure Redis Cache
demo
Azure Redis Cache
Redis + Auth + SSL
Monitoring
Alerts
Awesome tool: www.redsmin.com
Transactions
MULTI, EXEC, DISCARD, WATCH
No rollbacks (just discard queue)
Failures are because of you, not Redis
Optimistic locking with WATCH
Only execute transaction queue if watched keys did not change
Transactions
demo
Pub/Sub
(P)SUBSCRIBE, UNSUBSCRIBE, PUBLISH
Subscribe to a queue
SUBSCRIBE news (or PSUBSCRIBE news:*)
Send data to a queue
PUBLISH news “This just in!”
(optional) Keyspace notifications
http://www.redis.io/topics/notifications
CONFIG SET notify-keyspace-events KEA
PSUBSCRIBE '__key*__:*' (or __keyspace@0__:foo)
Pub/Sub
demo
Scripting
Run Lua scripts on Redis
http://www.redis.io/commands/eval
EVAL ‘return “Hello, World!”’ 0
Scripts are cached (SCRIPT FLUSH)
Scripts can be used as functions
Although we must pass the body all the time (or use SCRIPT LOAD +
EVALSHA)
Helper functions available!
Base, table, string, math, debug, struct, cjson, cmsgpack, redis.sha1hex
Scripting
demo
What if I need more memory?
Sharding!
On client (consistent hashing)
On server (Redis Cluster, not on Azure)
Using a proxy (Twemproxy - https://github.com/twitter/twemproxy)
var options = new ConfigurationOptions
{
EndPoints = { "my-server" },
Proxy = Proxy.Twemproxy
};
Patterns
When can I use Redis?
ASP.NET Output Caching (RedisAspNetProviders)
ASP.NET Session State
General-purpose cache
Table Storage secondary index
“Cache with benefits”
Pub/sub
Generally: when use case maps and data fits in RAM
When should I avoid Redis?
More data than can fit in RAM
Can use multiple, but even then: SUM(RAM) == max. data size
Data and query model fits well in a relational model
Materialize certain queries in Redis if needed
Avoid Redis for large objects...
...with lots of concurrent read/write operations
Counting stuff
How would you count “likes” if you were Facebook?
Table Storage
1 entity per likeable entity + per server instance for writes, sum entities for read
I/O and CPU time...
SQL
UPDATE ...
Locking...
Redis
INCR post:12345
(Every once in a while, check keys to persist)
Counting stuff (2)
How would you count “likes” if you were Facebook?
And how would you get the 5 most popular posts?
Use a sorted set
Elements are scored (= # of likes)
We can use ZREVRANGE to get the top X posts
ZREVRANGE posts:likes 0 5 withscores
Get the latest 5 product reviews
No need to go to the database
Use a Redis List, truncated at 5 items
Need more? Query the database
Rate limiting
API should only allows 5 requests per 60 seconds
Redis List
Record 5 latest requests
If we’re at 5, check the leftmost item versus current time
1 2 3 4 5
12:20:25 12:20:22 12:20:21 12:20:18 12:19:50
What’sUp?
Sending short messages between parties, how to
implement?
Pub/Sub:
Every user gets a subscription, others can send to that subscription
Server listens on all subscriptions to archive/persist messages
When user comes online, server can publish messages since last visit from
archive/a Redis list
Autocompletion
How to provide autocompletion over our million-
records product catalog?
SQL “LIKE”
Lucene.NET / ElasticSearch
Redis Sorted Set
Intersecting collections
“Which friends do we have in common?”
Algorithm could be:
Find friends that we have in common
Find friends they have in common
Score the # of connections
Sort
We have a series of bugs
Priority, Status, Title, ...
A user follows a few of these bugs
How to store?
How to query? (give me my top 5 bugs by priority)
Conclusion
Conclusion
Azure Cache
Redis is not just a cache
Data types
Transactions
Pub/sub
Scripting
Sharding/partitioning
Patterns
1 thing to remember: http://openmymind.net/redis.pdf
Thank you!
http://blog.maartenballiauw.be
@maartenballiauw
http://amzn.to/pronuget2

More Related Content

PPTX
Sherlock Homepage - A detective story about running large web services - WebN...
PPTX
Sherlock Homepage - A detective story about running large web services - NDC ...
PPTX
DNS for Developers - NDC Oslo 2016
PPTX
Get more than a cache back! - ConFoo Montreal
PPTX
10 performance and scalability secrets of ASP.NET websites
PPTX
Caching in Windows Azure
PDF
Data Analytics Service Company and Its Ruby Usage
PPTX
Web api scalability and performance
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - NDC ...
DNS for Developers - NDC Oslo 2016
Get more than a cache back! - ConFoo Montreal
10 performance and scalability secrets of ASP.NET websites
Caching in Windows Azure
Data Analytics Service Company and Its Ruby Usage
Web api scalability and performance

What's hot (20)

PPTX
Microsoft Azure Web Sites Performance Analysis Lessons Learned
PDF
Tuning Solr & Pipeline for Logs
PDF
Fluentd at Bay Area Kubernetes Meetup
PDF
Elasticsearch for Logs & Metrics - a deep dive
PDF
Use case for using the ElastiCache for Redis in production
PDF
Logging for Production Systems in The Container Era
PDF
Drupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google Cloud
PPTX
Reusable, composable, battle-tested Terraform modules
PDF
Tips and Tricks For Faster Asp.NET and MVC Applications
PDF
Tuning Solr for Logs
PDF
Terraform in deployment pipeline
PDF
Firebase slide
PPTX
Gruntwork Executive Summary
PPT
Python Deployment with Fabric
PDF
DOD 2016 - Rafał Kuć - Building a Resilient Log Aggregation Pipeline Using El...
PPTX
Solr Search Engine: Optimize Is (Not) Bad for You
PDF
Failsafe Mechanism for Yahoo Homepage
PDF
Automating Workflows for Analytics Pipelines
PDF
AWS DevOps - Terraform, Docker, HashiCorp Vault
PDF
5 Takeaways from Migrating a Library to Scala 3 - Scala Love
Microsoft Azure Web Sites Performance Analysis Lessons Learned
Tuning Solr & Pipeline for Logs
Fluentd at Bay Area Kubernetes Meetup
Elasticsearch for Logs & Metrics - a deep dive
Use case for using the ElastiCache for Redis in production
Logging for Production Systems in The Container Era
Drupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google Cloud
Reusable, composable, battle-tested Terraform modules
Tips and Tricks For Faster Asp.NET and MVC Applications
Tuning Solr for Logs
Terraform in deployment pipeline
Firebase slide
Gruntwork Executive Summary
Python Deployment with Fabric
DOD 2016 - Rafał Kuć - Building a Resilient Log Aggregation Pipeline Using El...
Solr Search Engine: Optimize Is (Not) Bad for You
Failsafe Mechanism for Yahoo Homepage
Automating Workflows for Analytics Pipelines
AWS DevOps - Terraform, Docker, HashiCorp Vault
5 Takeaways from Migrating a Library to Scala 3 - Scala Love
Ad

Viewers also liked (20)

PDF
Use Redis in Odd and Unusual Ways
PPTX
Redis Developers Day 2015 - Secondary Indexes and State of Lua
PDF
Build a Geospatial App with Redis 3.2- Andrew Bass, Sean Yesmunt, Sergio Prad...
PDF
Getting Started with Redis
PDF
RespClient - Minimal Redis Client for PowerShell
PDF
UV logic using redis bitmap
PDF
HIgh Performance Redis- Tague Griffith, GoPro
PPTX
RedisConf 2016 talk - The Redis API: Simple, Composable, Powerful
PPTX
Using Redis as Distributed Cache for ASP.NET apps - Peter Kellner, 73rd Stre...
PDF
Troubleshooting Redis- DaeMyung Kang, Kakao
PDF
Scalable Streaming Data Pipelines with Redis
PDF
Cloud Foundry for Data Science
PDF
Back your App with MySQL & Redis, the Cloud Foundry Way- Kenny Bastani, Pivotal
PPTX
Redis & MongoDB: Stop Big Data Indigestion Before It Starts
PDF
March 29, 2016 Dr. Josiah Carlson talks about using Redis as a Time Series DB
PDF
Redis High availability and fault tolerance in a multitenant environment
PPTX
Benchmarking Redis by itself and versus other NoSQL databases
PDF
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
PDF
Leveraging Probabilistic Data Structures for Real Time Analytics with Redis M...
PDF
Redis acc 2015_eng
Use Redis in Odd and Unusual Ways
Redis Developers Day 2015 - Secondary Indexes and State of Lua
Build a Geospatial App with Redis 3.2- Andrew Bass, Sean Yesmunt, Sergio Prad...
Getting Started with Redis
RespClient - Minimal Redis Client for PowerShell
UV logic using redis bitmap
HIgh Performance Redis- Tague Griffith, GoPro
RedisConf 2016 talk - The Redis API: Simple, Composable, Powerful
Using Redis as Distributed Cache for ASP.NET apps - Peter Kellner, 73rd Stre...
Troubleshooting Redis- DaeMyung Kang, Kakao
Scalable Streaming Data Pipelines with Redis
Cloud Foundry for Data Science
Back your App with MySQL & Redis, the Cloud Foundry Way- Kenny Bastani, Pivotal
Redis & MongoDB: Stop Big Data Indigestion Before It Starts
March 29, 2016 Dr. Josiah Carlson talks about using Redis as a Time Series DB
Redis High availability and fault tolerance in a multitenant environment
Benchmarking Redis by itself and versus other NoSQL databases
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Leveraging Probabilistic Data Structures for Real Time Analytics with Redis M...
Redis acc 2015_eng
Ad

Similar to Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo) (20)

PPTX
First Hive Meetup London 2012-07-10 - Tomas Cervenka - VisualDNA
PDF
Ceph at Spreadshirt (June 2016)
PDF
dba_lounge_Iasi: Everybody likes redis
ODP
OrientDB for real & Web App development
PPTX
What's new with enterprise Redis - Leena Joshi, Redis Labs
PPT
ArcReady - Architecting For The Cloud
PDF
RedisConf17 - Doing More With Redis - Ofer Bengal and Yiftach Shoolman
PDF
Using Redgate, AKS and Azure to bring DevOps to your Database
PDF
Using Redgate, AKS and Azure to bring DevOps to your database
PDF
Building Hopsworks, a cloud-native managed feature store for machine learning
PPTX
Big Data Goes Airborne. Propelling Your Big Data Initiative with Ironcluster ...
PDF
Sql on everything with drill
PPTX
Why databases cry at night
PDF
SfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
PDF
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
PDF
Serverless Go at BuzzBird
PDF
Real-time serverless analytics at Shedd – OLX data summit, Mar 2018, Barcelona
PDF
Big Data Analytics from Azure Cloud to Power BI Mobile
PDF
Experiences using CouchDB inside Microsoft's Azure team
PPTX
How it's made - MyGet (CloudBurst)
First Hive Meetup London 2012-07-10 - Tomas Cervenka - VisualDNA
Ceph at Spreadshirt (June 2016)
dba_lounge_Iasi: Everybody likes redis
OrientDB for real & Web App development
What's new with enterprise Redis - Leena Joshi, Redis Labs
ArcReady - Architecting For The Cloud
RedisConf17 - Doing More With Redis - Ofer Bengal and Yiftach Shoolman
Using Redgate, AKS and Azure to bring DevOps to your Database
Using Redgate, AKS and Azure to bring DevOps to your database
Building Hopsworks, a cloud-native managed feature store for machine learning
Big Data Goes Airborne. Propelling Your Big Data Initiative with Ironcluster ...
Sql on everything with drill
Why databases cry at night
SfDay 2019: Head first into Symfony Cache, Redis & Redis Cluster
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Serverless Go at BuzzBird
Real-time serverless analytics at Shedd – OLX data summit, Mar 2018, Barcelona
Big Data Analytics from Azure Cloud to Power BI Mobile
Experiences using CouchDB inside Microsoft's Azure team
How it's made - MyGet (CloudBurst)

More from Maarten Balliauw (20)

PPTX
Bringing nullability into existing code - dammit is not the answer.pptx
PPTX
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
PPTX
Building a friendly .NET SDK to connect to Space
PPTX
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
PPTX
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
PPTX
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
PPTX
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
PPTX
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
PPTX
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
PPTX
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
PPTX
Approaches for application request throttling - Cloud Developer Days Poland
PPTX
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
PPTX
Approaches for application request throttling - dotNetCologne
PPTX
CodeStock - Exploring .NET memory management - a trip down memory lane
PPTX
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
PPTX
ConFoo Montreal - Approaches for application request throttling
PPTX
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
PPTX
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
PPTX
DotNetFest - Let’s refresh our memory! Memory management in .NET
PPTX
VISUG - Approaches for application request throttling
Bringing nullability into existing code - dammit is not the answer.pptx
Nerd sniping myself into a rabbit hole... Streaming online audio to a Sonos s...
Building a friendly .NET SDK to connect to Space
Microservices for building an IDE - The innards of JetBrains Rider - NDC Oslo...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...
.NET Conf 2019 - Indexing and searching NuGet.org with Azure Functions and Se...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
Approaches for application request throttling - Cloud Developer Days Poland
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Approaches for application request throttling - dotNetCologne
CodeStock - Exploring .NET memory management - a trip down memory lane
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Approaches for application request throttling
Microservices for building an IDE – The innards of JetBrains Rider - TechDays...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
DotNetFest - Let’s refresh our memory! Memory management in .NET
VISUG - Approaches for application request throttling

Recently uploaded (20)

PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Machine learning based COVID-19 study performance prediction
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
Spectroscopy.pptx food analysis technology
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPT
Teaching material agriculture food technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
GamePlan Trading System Review: Professional Trader's Honest Take
NewMind AI Monthly Chronicles - July 2025
Machine learning based COVID-19 study performance prediction
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
cuic standard and advanced reporting.pdf
Transforming Manufacturing operations through Intelligent Integrations
Chapter 3 Spatial Domain Image Processing.pdf
Sensors and Actuators in IoT Systems using pdf
Electronic commerce courselecture one. Pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Spectroscopy.pptx food analysis technology
Advanced methodologies resolving dimensionality complications for autism neur...
NewMind AI Weekly Chronicles - August'25 Week I
Teaching material agriculture food technology
Understanding_Digital_Forensics_Presentation.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...

Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)

  • 1. Get more than a cache back! The Microsoft Azure (Redis) Cache Maarten Balliauw @maartenballiauw
  • 2. Who am I? Maarten Balliauw Antwerp, Belgium Software Engineer, Microsoft Founder, MyGet AZUG Focus on web ASP.NET MVC, Azure, SignalR, ... Former MVP Azure & ASPInsider Big passion: Azure http://blog.maartenballiauw.be @maartenballiauw Shameless self promotion: Pro NuGet - http://amzn.to/pronuget2
  • 5. Caching on Azure Windows Server: AppFabric (“Velocity”) (2009-2010) Azure (ASP.NET cache) “Shared Cache” (AppFabric cache, multi-tenant) Self-Hosted Dedicated Cache Managed Cache (the above, but managed by Microsoft and with an SLA) A bit of history...
  • 6. Caching on Azure 1920: Cache used to be a cache 2012: Cache became the go-to datastore Twitter stores 800 tweets / timeline in Redis New application types on Azure: PHP, Node, Java, ... Too much work to write AppFabric clients for all! http://www.redis.io/clients Way easier: just make it work on Windows and Azure New ways to develop applications
  • 8. Redis “Redis is an open source, BSD licensed, networked, single-threaded, in-memory key- value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.” REmote DIctionary Server
  • 9. Redis Key-value cache and store (value can be a couple of things) In-memory (no persistence, but you can) Single-threaded (atomic operations & transactions) Networked (it’s a server and it does master/slave) Some other stuff (scripting, pub/sub, Sentinel, snapshot, …) Things to remember
  • 10. So no persistence? Possible using a lot of I/O AOF (append-only files) RDB (Redis DB snapshots) With or without: all your data must fit in memory
  • 12. The Little Redis Book http://openmymind.net/redis.pdf By Karl Seguin
  • 13. Data types Type Example Key Example value String cache:/home <html><head><title>Home page</title> Hash categories:1 Field name description numproducts Member Books Books for sale 50000 Set categories:1:products 20 11 56 89 32 4 List products:20:comments [0] -> “...” [1] -> “...” [2] -> “...” Sorted set products:bestsellers Field Eye Patch Parrot Score 84632 82120 + Bitmap, Hyperloglog
  • 15. Data types Type Example Key Example value String cache:/home user:nextid <html><head><title>Home page</title> 2 Hash user:1 Field name handle Member Maarten @maartenballiauw Set user:1:followers 10 42 99 85 List user:1:timeline [0] -> { ... } [1] -> { ... } [2] -> { ... } Sorted set trending:no:tags Field #ndcoslo #redis Score 84632 82120 + Bitmap, Hyperloglog
  • 16. Keys Good practice: use a pattern for keys E.g. users:1:maarten Get by id: KEYS users:1:* GET ...... Get by name: KEYS users:*:maarten GET ...... O(N) operation – use with caution!
  • 17. But... .NET? Lots of options! http://www.redis.io/clients NuGet: ServiceStack.Redis StackExchange.Redis RedisAspNetProviders ...
  • 19. But... Azure? “It’s just Redis!” Main differences: auth mechanism and SSL support Use local for development from GitHub or NuGet (Redis-32 or Redis-64)
  • 21. Azure Redis Cache Redis + Auth + SSL Monitoring Alerts Awesome tool: www.redsmin.com
  • 22. Transactions MULTI, EXEC, DISCARD, WATCH No rollbacks (just discard queue) Failures are because of you, not Redis Optimistic locking with WATCH Only execute transaction queue if watched keys did not change
  • 24. Pub/Sub (P)SUBSCRIBE, UNSUBSCRIBE, PUBLISH Subscribe to a queue SUBSCRIBE news (or PSUBSCRIBE news:*) Send data to a queue PUBLISH news “This just in!” (optional) Keyspace notifications http://www.redis.io/topics/notifications CONFIG SET notify-keyspace-events KEA PSUBSCRIBE '__key*__:*' (or __keyspace@0__:foo)
  • 26. Scripting Run Lua scripts on Redis http://www.redis.io/commands/eval EVAL ‘return “Hello, World!”’ 0 Scripts are cached (SCRIPT FLUSH) Scripts can be used as functions Although we must pass the body all the time (or use SCRIPT LOAD + EVALSHA) Helper functions available! Base, table, string, math, debug, struct, cjson, cmsgpack, redis.sha1hex
  • 28. What if I need more memory? Sharding! On client (consistent hashing) On server (Redis Cluster, not on Azure) Using a proxy (Twemproxy - https://github.com/twitter/twemproxy) var options = new ConfigurationOptions { EndPoints = { "my-server" }, Proxy = Proxy.Twemproxy };
  • 30. When can I use Redis? ASP.NET Output Caching (RedisAspNetProviders) ASP.NET Session State General-purpose cache Table Storage secondary index “Cache with benefits” Pub/sub Generally: when use case maps and data fits in RAM
  • 31. When should I avoid Redis? More data than can fit in RAM Can use multiple, but even then: SUM(RAM) == max. data size Data and query model fits well in a relational model Materialize certain queries in Redis if needed Avoid Redis for large objects... ...with lots of concurrent read/write operations
  • 32. Counting stuff How would you count “likes” if you were Facebook? Table Storage 1 entity per likeable entity + per server instance for writes, sum entities for read I/O and CPU time... SQL UPDATE ... Locking... Redis INCR post:12345 (Every once in a while, check keys to persist)
  • 33. Counting stuff (2) How would you count “likes” if you were Facebook? And how would you get the 5 most popular posts? Use a sorted set Elements are scored (= # of likes) We can use ZREVRANGE to get the top X posts ZREVRANGE posts:likes 0 5 withscores
  • 34. Get the latest 5 product reviews No need to go to the database Use a Redis List, truncated at 5 items Need more? Query the database
  • 35. Rate limiting API should only allows 5 requests per 60 seconds Redis List Record 5 latest requests If we’re at 5, check the leftmost item versus current time 1 2 3 4 5 12:20:25 12:20:22 12:20:21 12:20:18 12:19:50
  • 36. What’sUp? Sending short messages between parties, how to implement? Pub/Sub: Every user gets a subscription, others can send to that subscription Server listens on all subscriptions to archive/persist messages When user comes online, server can publish messages since last visit from archive/a Redis list
  • 37. Autocompletion How to provide autocompletion over our million- records product catalog? SQL “LIKE” Lucene.NET / ElasticSearch Redis Sorted Set
  • 38. Intersecting collections “Which friends do we have in common?” Algorithm could be: Find friends that we have in common Find friends they have in common Score the # of connections
  • 39. Sort We have a series of bugs Priority, Status, Title, ... A user follows a few of these bugs How to store? How to query? (give me my top 5 bugs by priority)
  • 41. Conclusion Azure Cache Redis is not just a cache Data types Transactions Pub/sub Scripting Sharding/partitioning Patterns 1 thing to remember: http://openmymind.net/redis.pdf

Editor's Notes

  • #13: Start server Show config file and some of the options in there Connect client, mention on localhost it autoconnects as I’m using default ports and such Run some commands: get name set name “Maarten” get name getrange name 2 4 expire name 5 get name Explain simple commands, yet powerful (e.g. substring) Check config with “info” (also cache misses/hits etc.)
  • #16: Demo some of the data types. Here’s a bunch to choose from: String: get cache:/home set cache:/home "Home page" get cache:/home getrange cache:/home 2 5 expire cache:/home 5 get cache:/home incr site:visits incrby site:visits 6 Hash: hmset categories:1 name Books numproducts 4 hgetall categories:1 hincrby categories:1 numproducts 1 hget categories:1 name hset categories:1 numproducts 500 hgetall categories:1 Set: sadd categories:1:products 20 11 56 89 32 4 sadd categories:1:products 99 scard categories:1:products sadd categories:2:products 20 11 sinter categories:1:products categories:2:products sdiff categories:1:products categories:2:products List: rpush products:20:comments "Awesome product!" rpush products:20:comments "This sucks." rpush products:20:comments "Yarr!" lindex products:20:comments 1 llen products:20:comments brpop products:20:comments queue 0 #blocking at the end! pub/sub? Sorted Set: zadd products:bestsellers 100 "Eye Patch" 10 "Parrot" 1 "Ship" zrevrange products:bestsellers 0 1 zrevrank products:bestsellers "Ship" zscore products:bestsellers "Ship"
  • #20: Create a quick console app Install StackExchange.Redis ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"); // explain: keep this one! var database = redis.GetDatabase(); // explain: can be disposed andall database.StringSet("test", "Just a quick test"); Console.WriteLine(database.StringGet("test")); Console.ReadLine();
  • #22: Create a Redis cache through portal.azure.com Explain Standard vs. Basic (replica, but data loss still possible) Update previous sample ConnectionMultiplexer.Connect("maartenba.redis.cache.windows.net:6379,password=/tvkIbDBTyhu8vJueOt150iP3kzIXTb/u2dTB5PxJsM="); In the portal, show configuration of maxmemory In the portal, show alerts and notifications In the portal, show stats / hits / misses etc Show this connecting using the redis-cli, too (redis-cli –h host –a pass) And there is also... www.redsmin.com (login, explain some of the things we can see here)
  • #25: Connect to localhost, perhaps flushall first SET where “Sweden” SET conference “Unknown” SET attendees 0 Connect a second client MULTI INCRBY attendees 100 SET conference “CloudBurst” EXEC Worked fine! Now let’s do this on client 1: WATCH attendees MULTI INCRBY attendees 100 And on client 2: SET attendees 99 And on client 1: EXEC .NET: var transaction = redis.GetDatabase().CreateTransaction(); transaction.AddCondition(Condition.KeyExists("foo")); transaction.StringSetAsync("foo", "bar"); bool committed = transaction.Execute();
  • #27: Use two clients Client 1: SUBSCRIBE news Client 2: PUBLISH news “This just in” Let’s do that in .NET: ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"); ISubscriber subscriber = redis.GetSubscriber(); subscriber.Subscribe("news", (channel, message) => { Console.WriteLine("News: {0}", (string)message); }); ISubscriber publisher = redis.GetSubscriber(); publisher.Publish("news", "This just in!"); Console.ReadLine(); Send a message from one of the clients, too Keyspace notifications: CONFIG SET notify-keyspace-events KEA PSUBSCRIBE '__key*__:*'
  • #29: Do some scripts in the sample project