Redis · Chapter 12 of 26
Sessions
By the end of this chapter you can keep logged-in fans in Redis: a session id from crypto.randomUUID(), a session hash with a TTL, expiry that slides forward while the fan is active, logging out of one device, and logging out of every device at once. 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
A fan logs in once and then taps through the app all evening: the match centre, a contest, their team, the leaderboard. Each of those requests has to know who is asking, without the password. So at login GullyXI makes a session: a random id the phone keeps and sends with every request, and, on the server's side, what that id stands for (which fan, their name, when they logged in).
The session must live somewhere every app server can read. On match night GullyXI runs twenty app servers behind a load balancer, and each request goes to whichever server is free. Last season sessions sat in each server's memory, so a fan who logged in on one server and tapped once landed on another that had never heard of them: "please log in again", at the toss. Gurpreet counted forty thousand of those in ten minutes. And every deploy restarted the servers and logged everyone out.
Redis fixes both: one place all servers share, that keeps sessions through a deploy, and that ends idle sessions on its own with a TTL.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
session.js: log in, and read the session back
In session.js, write createSession(redis, db, fanId, now). Make the id with crypto.randomUUID() (from node:crypto) and store the session under session:<id> as a hash with four fields: fan (the fan's id), name (from db.getFan(fanId), Ananya Mishra for u1001), created and seen (both now, in milliseconds). Give session:<id> a TTL of 1800 seconds (the check accepts 1795 to 1800) and add the id to the set fan:<fanId>:sessions. Send the hash, the TTL and the set in one MULTI (the check counts the MULTIs Redis ran). Return the id; two logins get two different ids. For a fan who does not exist (getFan answers null, as for u9999), return null and store nothing.
Then write getSession(redis, sessionId): the session's fields as an object, or null for a session that does not exist (not an empty object).
- Task 2
touch.js: keep an active fan logged in
In touch.js, write touchSession(redis, sessionId, now), which the app calls on every request (sliding expiry). For a live session, set the TTL of session:<id> back to 1800 seconds (the check accepts 1795 to 1800), set its seen field to now (in milliseconds), leave the other fields as they are, and return true.
For a session that has expired or never existed, return false and leave nothing behind: no key session:<id> may exist afterwards.
- Task 3
logout.js: log out here, and log out everywhere
Sessions are hashes session:<id> with a fan field, and each fan's session ids are in the set fan:<fanId>:sessions (the check makes them). In logout.js, write logout(redis, sessionId): delete session:<id>, take the id out of its fan's set (the fan is in the hash), and return true, or false if the session was not there.
Then write logoutEverywhere(redis, fanId): delete every session of that fan and the set fan:<fanId>:sessions itself, and return how many sessions it really ended. An id can stay in the set after its session expired; it does not count. A fan with no sessions (u1003) gets 0, without an error. Other fans' sessions and sets stay as they are.
- Task 4 · interview question
Interview: two-servers.js, two app servers, one login
In two-servers.js, login(redis, db, fanId) and whoIs(redis, sessionId) keep sessions in a Map in the server's memory, so a fan who logs in on one app server is unknown on the others. Keep the two functions and what they return, and move the sessions into Redis.
login stores session:<id> (id from crypto.randomUUID()) as a hash with the fields fan and name (from db.getFan), with a TTL of 1800 seconds (the check accepts 1795 to 1800), and returns the id, or null for a fan who does not exist. whoIs returns the fan's name, or null for a session that does not exist. The check loads your file as two separate app servers, and once more as a restarted server: a session made on one must be found on all.
Farhan will ask: why do sessions live in Redis when GullyXI runs many app servers, and what would a sticky load balancer cost you instead?
What you will learn
- crypto.randomUUID(): a session id no one can guess.
- A session hash: the session's fields in one key, with a TTL.
- Reading it back: HGETALL, and why a missing hash is {} in ioredis.
- Sliding expiry: every request moves the TTL forward.
- A set of a fan's sessions: logging out of one device, or all of them.
- DEL with many keys, and the error when there are none.
More in Redis from Node.js
Build "Sessions" 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.