infuerno.github.io

Redis

Reference: http://openmymind.net/redis.pdf

Databases

Databases are simply identified by a number. The default is 0. Change to another database using select 1.

Data structures

String (scalar)

Useful for:

Common operations include:

Hashes

Useful for:

Common operations:

Lists

Useful for:

Common operations:

Sets

Useful for:

Common operations:

Sorted sets

Common operations:

Memory and persistence

Redis runs in memory and periodically persists to disk. By default Redis saves the whole database every 60 seconds if 1000 or more keys have changed up to 15 minutes if less than 9 keys have changed.

In addition to snapshotting Redis can run in append mode whereby an append-only file is updated every time a key changes.

Leveraging data sturctures

Lookup by value

By default redis only allows lookups by key. In order to perform queries using values, an seperate structure needs to be defined which makes these values in one object, keys in another. Hashs are perfect these indexes.

set users:9001 '{"id": 9001, "email": "leto@dune.gov", ...}' hset users:lookup:email leto@dune.gov 9001

get users:9001 to look up someone by key hget users:leto@dune.gov to get someone’s key by email and then use this to lookup via key

Remember, such indexes need to be created / managed / updated / deleted manually.

Maintaining references and indexes

sadd friends:leto ghanima paul chani jessica

In the set above, the values are likely also keys to the details of that person. If chani changes her name, or deletes her account there is no easy way to work out which sets we need to update in order to ensure the reference set is still consistent. Using a numeric id would be preferable for the set. But this doesn’t resolve managing account deletions. Here a reverse index would need to also be maintained.

sadd friends_of:chani leto paul

Round trips and pipelining

Making round trips to the database are a common pattern in Redis. There are certain features in Redis which can be leveraged to get the most out of this pattern.

Transactions

*** BOTTOM OF PAGE 18 - DON’T UNDERSTAND***

Keys anti-pattern

The keys <pattern> command usefully takes a pattern and returns all matching keys. However, it does this by scanning through all existing keys and is therefore very slow. Avoid using this in production code and instead use a hash etc to provide an index for data retrieval on specific criteria.

Beyond the data structures

Expiration

Pub and sub

Monitor and slow log

Sort