get more than a cache back! - confoo montreal

35
Redis Get more than a cache back! Maarten Balliauw @maartenballiauw

Upload: maarten-balliauw

Post on 12-Apr-2017

123 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: Get more than a cache back! - ConFoo Montreal

RedisGet more than a cache back!Maarten Balliauw@maartenballiauw

Page 2: Get more than a cache back! - ConFoo Montreal

Who am I?

Maarten Balliauw Antwerp, Belgium Developer Advocate, JetBrains Founder, MyGet Focus on web & cloud http://blog.maartenballiauw.be @maartenballiauw

Page 3: Get more than a cache back! - ConFoo Montreal

Agenda

Redis Data types Transactions Pub/sub Scripting Sharding/partitioning Patterns

Page 4: Get more than a cache back! - ConFoo Montreal

Redis

Page 5: Get more than a cache back! - ConFoo Montreal

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

Page 6: Get more than a cache back! - ConFoo Montreal

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

Page 7: Get more than a cache back! - ConFoo Montreal

Persistence?

Dump memory to disk (faster restore after restart)

AOF (append-only files) RDB (Redis DB snapshots)

With or without: all your data must fit in memory

Page 8: Get more than a cache back! - ConFoo Montreal

Redis 101demo

Page 9: Get more than a cache back! - ConFoo Montreal

The Little Redis Book

http://openmymind.net/redis.pdf

By Karl Seguin

Page 10: Get more than a cache back! - ConFoo Montreal

Data types

Type Example Key Example valueString cache:/home <html><head><title>Home

page</title>Hash categories:1 Field

namedescriptionnumproducts

MemberShipsPirate ships for sale50000

Set categories:1:products 20 11 56 89 32 4List products:20:comments [0] -> “That skull flag is awesome!”

[1] -> “Parrot bit my finger, not happy!”[2] -> “Parrot keeps swearing at me.”

Sorted set products:bestsellers FieldEye PatchParrot

Score8463282120

+ Bitmap, Hyperloglog

Page 11: Get more than a cache back! - ConFoo Montreal

Data typesdemo

Page 12: Get more than a cache back! - ConFoo Montreal

Data types

Type Example Key Example valueString cache:/home

user:nextid<html><head><title>Home page</title>2

Hash user:1 Fieldnamehandle

MemberMaarten@maartenballiauw

Set user:1:followers 10 42 99 85List user:1:timeline [0] -> { ... }

[1] -> { ... }[2] -> { ... }

Sorted set trending:no:tags Field#ndcoslo#redis

Score8463282120

+ Bitmap, Hyperloglog

Page 13: Get more than a cache back! - ConFoo Montreal

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!

Page 14: Get more than a cache back! - ConFoo Montreal

But... client-side?

Lots of options! http://www.redis.io/clients

Page 15: Get more than a cache back! - ConFoo Montreal

Connecting to Redis (C# / Node – pick one!)demo

Page 16: Get more than a cache back! - ConFoo Montreal

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

Page 17: Get more than a cache back! - ConFoo Montreal

Transactionsdemo

Page 18: Get more than a cache back! - ConFoo Montreal

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 notificationshttp://www.redis.io/topics/notifications

CONFIG SET notify-keyspace-events KEA PSUBSCRIBE '__key*__:*' (or __keyspace@0__:foo)

Page 19: Get more than a cache back! - ConFoo Montreal

Pub/Subdemo

Page 20: Get more than a cache back! - ConFoo Montreal

Scripting

Run Lua scripts on Redishttp://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

Page 21: Get more than a cache back! - ConFoo Montreal

Scriptingdemo

Page 22: Get more than a cache back! - ConFoo Montreal

What if I need more memory?

Sharding On client (consistent hashing) Using a proxy (Twemproxy -

https://github.com/twitter/twemproxy) Cluster On server (Redis Cluster) tip: always connect to >= 2 nodesvar Redis = require('ioredis');

var cluster = new Redis.Cluster([ { port: 6380, host: '127.0.0.1' }, { port: 6381, host: '127.0.0.1' }]);

cluster.set('foo', 'bar');cluster.get('foo', function (err, res) { // ... });

Page 23: Get more than a cache back! - ConFoo Montreal

Patterns

Page 24: Get more than a cache back! - ConFoo Montreal

When can I use Redis?

Output cache Session state General-purpose cache (e.g. for database) “Cache with benefits” Pub/sub Generally: when use case maps and data fits in RAM

Page 25: Get more than a cache back! - ConFoo Montreal

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

Page 26: Get more than a cache back! - ConFoo Montreal

Counting stuff

How would you count “likes” if you were Facebook?

SQL UPDATE posts SET likes = likes + 1 WHERE postid = 1234 Locking! Will slow down the application... Redis INCR post:12345 (Every once in a while, check keys to persist)

Page 27: Get more than a cache back! - ConFoo Montreal

Counting stuff (+ popularity)

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

Page 28: Get more than a cache back! - ConFoo Montreal

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

Page 29: Get more than a cache back! - ConFoo Montreal

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 512:20:25 12:20:22 12:20:21 12:20:18 12:19:50

Page 30: Get more than a cache back! - ConFoo Montreal

Autocompletion

How to provide autocompletion over our million-records product catalog?

SQL “LIKE” Lucene / ElasticSearch Redis Sorted Set

Page 31: Get more than a cache back! - ConFoo Montreal

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

Page 32: Get more than a cache back! - ConFoo Montreal

Sort

We have a series of bugsPriority, Status, Title, ...

A user follows a few of these bugsHow to store?How to query? (give me my top 5 bugs by priority) hset bugs:1 priority 5

hset bugs:2 priority 2hset bugs:3 priority 1

SORT bugsifollow BY bugs:*->priority

Page 33: Get more than a cache back! - ConFoo Montreal

Conclusion

Page 34: Get more than a cache back! - ConFoo Montreal

Conclusion

Redis is not just a cache Data types Transactions Pub/sub Scripting Sharding/partitioning Patterns 1 thing to remember: http://openmymind.net/redis.pdf

Page 35: Get more than a cache back! - ConFoo Montreal

Thank you!http://blog.maartenballiauw.be@maartenballiauw