0
0
RedisHow-ToBeginner · 4 min read

How to Use Redis for API Cache: Simple Guide

Use Redis to store API responses temporarily by saving the data with a unique key and setting an expiration time. When the API is called, first check if the cached data exists in Redis; if yes, return it directly, otherwise fetch fresh data, store it in Redis, and then return it.
📐

Syntax

To use Redis for API caching, you mainly use commands to set and get cached data. The key parts are:

  • SET key value EX seconds: Stores the value with a key and sets expiration time in seconds.
  • GET key: Retrieves the cached value by key.

This lets you save API responses and automatically expire them after some time.

redis
SET api_cache:user:123 "{\"name\":\"Alice\",\"age\":30}" EX 300
GET api_cache:user:123
Output
"{\"name\":\"Alice\",\"age\":30}"
💻

Example

This example shows a simple Node.js API caching with Redis. It checks if cached data exists for a user, returns it if found, or fetches fresh data, caches it, and returns it.

javascript
import { createClient } from 'redis';
import express from 'express';

const app = express();
const client = createClient();

client.connect();

app.get('/user/:id', async (req, res) => {
  const userId = req.params.id;
  const cacheKey = `user:${userId}`;

  // Try to get cached data
  const cachedData = await client.get(cacheKey);
  if (cachedData) {
    return res.json({ source: 'cache', data: JSON.parse(cachedData) });
  }

  // Simulate fetching fresh data
  const freshData = { id: userId, name: 'Alice', age: 30 };

  // Cache the fresh data for 5 minutes
  await client.set(cacheKey, JSON.stringify(freshData), { EX: 300 });

  res.json({ source: 'api', data: freshData });
});

app.listen(3000, () => console.log('Server running on port 3000'));
Output
{"source":"api","data":{"id":"123","name":"Alice","age":30}}
⚠️

Common Pitfalls

Common mistakes when using Redis for API caching include:

  • Not setting an expiration time, causing stale data to persist indefinitely.
  • Using non-unique keys, which can overwrite different API responses.
  • Ignoring cache misses and not falling back to fresh data fetching.
  • Storing large or complex objects without serialization, leading to errors.

Always serialize data (e.g., JSON.stringify) before caching and deserialize (e.g., JSON.parse) when reading.

javascript
/* Wrong: No expiration and no serialization */
client.set('user:123', {name: 'Alice'});

/* Right: Set expiration and serialize */
client.set('user:123', JSON.stringify({name: 'Alice'}), { EX: 300 });
📊

Quick Reference

CommandPurposeExample
SET key value EX secondsStore value with expirationSET user:1 "{\"name\":\"Bob\"}" EX 600
GET keyRetrieve cached valueGET user:1
DEL keyDelete cached valueDEL user:1
EXPIRE key secondsSet expiration on existing keyEXPIRE user:1 300

Key Takeaways

Always check Redis cache before fetching fresh API data to improve speed.
Set expiration times on cached data to avoid stale responses.
Use unique keys for different API endpoints or parameters.
Serialize data before caching and deserialize after retrieving.
Handle cache misses gracefully by fetching and caching fresh data.