Redis · Chapter 9 of 26

Node.js and ioredis

By the end of this chapter you can talk to Redis from a Node.js program with ioredis: connect from REDIS_URL, send any command you learned in class 1 as a method that returns a promise, read its reply as plain JavaScript, catch Redis's errors, walk keys with scanStream, and close the program cleanly with one client for the whole app. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Redis from Node.js
  • 4 tasks
  • Redis
  • In the all labs plan

The first 2 chapters of Redis are free. This one comes with the all labs plan.

Why you need this

GullyXI's app servers are Node.js programs. Every fan who opens the match centre, joins a contest or refreshes a board is a request to one of them, and it is that code, not a person at redis-cli, that has to send SET, HINCRBY or ZRANGE. Farhan wants the whole class 1 toolkit available from JavaScript, and Gurpreet wants it done without the mistake that paged her last season: app servers that opened a new connection to Redis for every request, until Redis had thousands of them.

A .redis file runs top to bottom and cannot decide anything: in chapter 8 the file watched the last spot but you made the decision. A program can read a reply, look at it and choose what to send next. That is what the rest of the lab builds on.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    connect.js: connect from REDIS_URL

    Export two functions from connect.js. connect() makes and returns a new ioredis client for the Redis whose address is in process.env.REDIS_URL (read it from there, never type it in: the Check's Redis runs on another port and REDIS_URL points at it).

    health(redis) asks the Redis it is given two things and returns an object { ping, keys }: ping is what PING answers ('PONG'), and keys is how many keys that Redis holds, as a number (3 when it holds three keys, 4 after a fourth is added).

  2. Task 2

    player-card.js: save and load a player's card

    A player from GullyXI's database looks like { id: 'P150', name: 'Sourav Chatterjee', team: 'CHE', role: 'BAT', credits: 10.5 }.

    savePlayer(redis, player) stores the player as a hash under the key player:<id> (player:P150) with exactly the fields name, team, role and credits; the id is in the key, not in a field.

    loadPlayer(redis, id) reads player:<id> back and returns the same object as the database's: id, name, team, role, and credits as a number (10.5, not '10.5'). For a player who is not in Redis (P999) it returns null. The Check saves and loads P150 and P163.

  3. Task 3

    match-keys.js: every key of a match, with scanStream

    matchKeys(redis, matchId) returns an array, sorted A to Z, of every key (of any type) that starts with match:<matchId>: with the colon, each key once. On the Check's Redis, which holds 3,000 other keys, matchKeys(redis, 2003) returns match:2003:status, match:2003:toss, match:2003:venue, match:2003:views and match:2003:watchers, never match:20030:status; for a match with no keys it returns an empty array.

    Use ioredis's scanStream. KEYS is not allowed: the Check counts the commands Redis ran, and needs no KEYS and more than one SCAN.

  4. Task 4 · interview question

    Interview: one-client.js, one client for the app

    one-client.js counts every open of a match in stats:<matchId>:app_opens, but every call to countOpen makes its own client and never closes it: after 50 opens Redis has 50 connections from it.

    Fix it, keeping its three exports. getClient() returns the app's one client: made from process.env.REDIS_URL on the first call, and the same object on every call after. countOpen(matchId) adds 1 to stats:<matchId>:app_opens with that client and returns the new count. closeClient() closes that client and forgets it, so a later getClient() makes a new one.

    The Check runs 50 countOpen(2001) calls at once: they must return 1 to 50, leave stats:2001:app_opens at 50 and open one connection in all. After closeClient() no connection from your code is left, and countOpen(2002) still works (it answers 1).

    Farhan will ask: why one client for the whole app, and not one per request? What does each new client cost?

What you will learn

  • ioredis and new Redis(process.env.REDIS_URL): a client, and what it does when it connects.
  • Commands as methods: set, get, hset, incr, each returning a promise.
  • Replies as JavaScript: strings, numbers, null, arrays, and hgetall as an object.
  • ReplyError: an error reply as a rejected promise.
  • quit and disconnect, and connection events in a line.
  • scanStream: SCAN in a loop, done for you.
  • One client for the app, and the try-it block with import.meta.main.

More in Redis from Node.js

Build "Node.js and ioredis" yourself

GullyXI, a Pune fantasy cricket app, falls over on match night. You make it fast with Redis. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Redis are free. This one comes with the all labs plan.