Introduction to Redis
Tags: redis, node, caching, webdev
Published: 2018-07-08 17:27:05

---
title: Introduction to Redis
published: true
description: A look at NoSQL memory-optimized database
tags: redis,node,caching,webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/juz1vyzzc0zp7ho41p3q.jpeg
---

For a high traffic web service, it becomes a necessity for it to leverage some kind of caching mechanism. Caching is a way of storing computed data in memory so that future requests can be fulfilled right away. It also helps in avoiding any round trips to the data layer and computations on the application side if implemented with the right strategy. Redis and Memcached are two most popular memory-based stores available. In this post, we will explore some key concepts of Redis and go through some basic commands. Besides caching, Redis can be also used for other applications where there is a need for fast and frequent access to data.

### Redis

![redis logo](https://thepracticaldev.s3.amazonaws.com/i/787xlgwc2hhq3ctzxcvs.png)

Redis is an in-memory data structure store supporting many data types like strings, hashes, sets, sorted sets, etc. Essentially, it is a key-value store.

Every type of value in Redis is stored against a key that is binary safe and it can be anything from an empty string to long hash string. Every application should follow a predetermined schema for naming Redis keys to avoid any naming conflicts.

#### Setting up Redis

Like every database, Redis contains a server for storing data in memory and clients which will execute commands against a server.
For setting up the server on your local machine, I will recommend using Docker as it is easy to get started. If you have Docker daemon running on your machine, run the following command:

```
docker run --rm -it --name local-redis -p 6379:6379 redis
```

This will run a Docker container with name local-redis on your localhost with port 6379. It uses the official Redis docker image to run the container.

For the client, we can use the redis-cli for executing commands from a console on the Redis server. Open a new tab, and execute the following command to start a redis-cli session connected to local docker Redis server instance:

```
docker run -it --link local-redis:redis --rm redis redis-cli -h redis -p 6379
```

Now we can start executing some basic Redis commands.


### Commands

* *Setting* a value:

    Syntax: `SET <key> <value>`
    Example: `SET firstname Albert`

* *Retrieve* a value:

    Syntax: `GET <key>`
    Example: `GET firstname`

* Check whether a key *exists*:

    Syntax: `EXISTS <key>`

* *Deleting* a key:

    A key can be removed along with its associated memory using:
    `DEL <key>`
    This is a synchronous blocking operation.

    A better way to remove keys will be to unlink them whose associated memory can be collected by a garbage collector later on.
    `UNLINK <key>`

* Setting a *time to expire* for key:

    `EXPIRE <key> <seconds>`
    `PEXPIRE <key> <milliseconds>`

* *Setting* a key with check for *existence* and *expiry* in one go:

    Syntax: `SET <key> <value> <EX seconds>|<PX milliseconds> NX|XX`

    NX - set only when a key does not exist.
    XX - set only when key already exists.
    EX - sets expire time for the key in seconds.
    PX - sets expire time for the key in milliseconds.

    Example:

    `SET firstname Albert EX 10 NX`

    This will set the key firstname with string value "Albert" with an expiry time of 10 seconds only if the key does not exist.

* *Increment* or *Decrement* an integer value:

    Redis provides a convenient way to increment or decrement integer values that may be used as counters.

    Syntax:
    `INCR <key>`
    `DECR <key>`
    `INCRBY <key> <increment value>`
    `DECRBY <key> <decrement value>`

    Example:
    `SET counter 4`
    `INCRBY counter 6`

    counter key will hold the value 4 initially, and after the second command, it will get incremented to 10.

All the above mentioned commands just deal with storing and manipulating of string or integer values. There are other data structure values such as hashes, sets, bit arrays, etc. that can be used to solve complex problems.

#### Real World Example

In a real-world application, you can use various programming language specific [redis clients](https://redis.io/clients) available for interacting with your Redis server from the application code.

We will be writing a simple Node based application that exposes an endpoint for getting user info against an userid. A JSON file will act as our datastore to keep things as simple as possible.

* First, initialise a NPM repository by running `npm init` and install *express* and *redis* as dependencies.
* Now, make a redis helper file that forms an instance of the redis client connected to our Redis server. We are also writing some cache helper methods here for our route handlers.
    
    ![redis cache helper file](https://thepracticaldev.s3.amazonaws.com/i/yvnh0ig59puaqj8xduyn.png)

* In main app file, write a route handler that accepts an userid against which the user info is to be retrieved. Next, form a unique redis key using the userid. This key will always be the same for every request for a given userid. Check for existence of this key in the Redis cache, and return the response if found.


    ![main file index.js](https://thepracticaldev.s3.amazonaws.com/i/29fg2n4l4900x41gmhgz.png)

* Else, we will query the data from our data source and set the response data to Redis cache before sending it back as a response.

To have a look at the full code and tinker around with it, you can clone the following repository:

{% github https://github.com/divyanshutomar/hello-redis %}

Congratulations! You have now learned the basics of Redis. If you'd like to take a deep dive, please have a look at the official [redis docs](https://redis.io/documentation).

Thank you for following along and I hope this post would have been useful for you.
Do follow me on [Twitter](https://twitter.com/divyanshutomar) to receive updates on such topics.