AI Computer Institute
Expert-curated CS & AI curriculum aligned to CBSE standards. A bharath.ai initiative. About Us

Redis: Speed Up Your Apps with Caching

📚 Backend Development⏱️ 24 min read🎓 Grade 12
✍️ AI Computer Institute Editorial Team Updated: August 2026 CBSE-aligned · Peer-reviewed · 24 min read
Content curated by subject matter experts with IIT/NIT backgrounds. All chapters are fact-checked against official CBSE/NCERT syllabi.

Ask a friend "what is 47 times 83?" and watch them work it out on paper: multiply, carry, add, multiply again. It takes a few seconds. Now ask the same question again, five seconds later. Does your friend redo the whole calculation? No — they just say "3901, I already told you that" and answer instantly. They didn't recompute the answer; they remembered it. That one-word difference between "recompute" and "remember" is the entire idea behind caching, and it is the reason a technology called Redis runs inside almost every large website and app you use, from ticket-booking portals to UPI payment apps to cricket score trackers.

A Real Traffic Jam: Checking Train Seats During Tatkal Booking

Here is a scenario every Indian student has either lived through or heard about from a parent. Tatkal booking opens on the IRCTC website at 10:00 AM for AC classes. In the first sixty seconds, tens of thousands of people all try to check the same thing: "How many seats are left in coach B4 of train 12951?" Every single one of those requests looks almost identical — same train number, same coach, same question — just asked by a different person at almost the same moment.

Now think about what happens on the server side if every one of those questions is answered by going all the way to the main database. A database is built to store data safely and permanently, which usually means writing to and reading from a disk (even a fast SSD disk). Disks are reliable, but compared to computer memory (RAM), they are slow. If 50,000 people ask the exact same question about the exact same train within the same second, and the server recalculates the seat count from the database every single time, the database gets crushed under repeated, identical work. The seat count for that train hasn't changed between request 1 and request 2 — but the server did the same expensive lookup twice, then fifty thousand times.

This is exactly the "recompute vs. remember" problem. The fix is: compute the answer once, store it somewhere very fast to read from, and let the next 49,999 people read that stored answer instead of repeating the expensive database lookup. That fast, temporary storage layer is called a cache, and Redis is the most widely used tool for building one.

Why RAM Beats Disk: The Real Speed Gap

To understand why caching works, you need to understand a fact about computer hardware: not all storage is equally fast. A computer has (at least) two very different places to keep data while it is running:

  • RAM (Random Access Memory) — an electronic circuit that holds data as long as power is on. It has no moving parts and no need to "seek" to a location; any address can be read in roughly the same tiny amount of time.
  • Disk (SSD or hard disk) — built to hold data permanently, even when the power is off. This durability comes at the cost of speed, especially for older spinning hard disks, which must physically move a read head.

Engineers who work on large systems often quote a rough rule of thumb (these are order-of-magnitude approximations that vary by hardware generation, not exact benchmarks, but the gap they describe is real and important): reading one small piece of data from RAM takes on the order of 100 nanoseconds (0.0000001 seconds). Reading the same size of data from a fast SSD takes on the order of 100 microseconds — about a thousand times slower than RAM. Reading it from an old-style spinning hard disk, which has to physically move a needle-like head to the right spot, can take around 10 milliseconds — roughly one hundred thousand times slower than RAM.

You don't need to memorise these exact numbers. What you must understand is the shape of the gap: RAM is not "a little" faster than disk, it is faster by several orders of magnitude — the same kind of gap as the difference between looking something up in a book you're holding open versus walking to another building to fetch it from an archive. Redis takes advantage of this gap by keeping data in RAM instead of on disk, which is why it is often called an in-memory data store.

What Exactly Is Redis?

Redis stands for REmote DIctionary Server. It was created in 2009 by the Italian programmer Salvatore Sanfilippo, who needed a fast way to store data for a real-time web analytics tool he was building and found existing databases too slow for that job. Redis is:

  • A key-value store — think of it as a giant, shared dictionary. You give it a key (a name, like seat:12951:B4) and it hands back the matching value (like "23"), or lets you set that value. This is exactly the same idea as a phone contacts app: you type a name (key) and instantly get the phone number (value) — you never scan through every contact one by one.
  • In-memory — the data mostly lives in RAM, which is why reads and writes are extremely fast (commonly under a millisecond).
  • A separate server — Redis is not a Python dictionary living inside one program. It runs as its own program (often on its own machine), and many different application servers can all connect to the same Redis instance and share the same cached data. That's the "Remote" and "Server" part of its name.

Internally, Redis stores its keys in a hash table — the same data structure your CBSE Computer Science textbook may describe when discussing dictionaries or hashmaps. A hash table gives average-case O(1) time complexity for lookups: whether Redis is holding 100 keys or 100 million keys, fetching one key by name takes roughly the same tiny amount of time, because the key is converted (hashed) directly into a memory address instead of being searched for. Compare this to scanning an unindexed list of records on disk, which can take time proportional to how many records exist (O(n)), on top of the disk-speed penalty described above. Redis is fast for two independent reasons: the hardware it uses (RAM) and the data structure it uses (hash tables).

How an App Actually Uses Redis: The Cache-Aside Pattern

Redis is almost never used by itself — it sits in front of a regular, permanent database (like MySQL or PostgreSQL) and intercepts repeated requests before they reach it. The most common way to wire this together is called the cache-aside pattern (also called "lazy loading"), and it works in five steps:

  1. The app server receives a request for some piece of data (e.g. "seat availability for train 12951, coach B4").
  2. The app server first asks Redis: "do you have a value stored for this key?"
  3. If Redis has it (a cache hit), it returns the value immediately, in well under a millisecond. The main database is never touched.
  4. If Redis does not have it (a cache miss) — either because it was never asked before, or because the stored value expired — the app server queries the slower main database, gets the real answer, and writes that answer into Redis before responding, so the next request for the same key becomes a cache hit.
  5. The app server sends the response back to whoever asked.

Here is that flow drawn out. Notice there are two very different paths a request can take — the short, fast path through Redis alone, and the long, slow path that must also visit the database:

Student's Browser App Server (backend code) Redis Cache lives in RAM key to value, O(1) lookup Main Database lives on disk e.g. MySQL, PostgreSQL 1. Request 5. Response 2. GET key 3a. HIT (~0.1 ms) 3b. MISS (~200 ms) 4. SETEX, TTL 5s

Follow the two paths in the diagram. On a hit (green dashed line), the app server never goes near the database at all — it asks Redis and gets an answer in a fraction of a millisecond. On a miss (orange dashed line), the app server has to make the slow trip to the database, and only after getting the real answer does it write that answer into Redis (purple line) so the next request for the same key becomes a hit.

Worked Example: How Much Load Does Caching Actually Remove?

Let's put real numbers on this so the benefit isn't just a vague claim of "faster." Imagine a school's exam datesheet portal. On the morning results are announced, 500 students each refresh the datesheet page once every 10 seconds, and they keep doing this for a full hour (3,600 seconds). Fetching and formatting the datesheet from the database takes 200 milliseconds of real database work each time it's done.

First, work out the total number of requests the server receives:

Requests per student = 3600 seconds / 10 seconds = 360 requests
Total requests (500 students) = 500 x 360 = 180,000 requests

Without a cache, every single one of those 180,000 requests goes straight to the database, and each one costs 200 ms of database time:

Total database work = 180,000 x 0.2 s = 36,000 seconds of DB processing

That's 36,000 seconds of cumulative database work squeezed into a 3,600-second (one hour) window — ten times more work than the window allows for. The database doesn't have ten copies of itself to run in parallel forever, so requests start queuing up and the whole portal slows down or times out for everyone, exactly like a traffic jam forming because one lane is trying to carry ten lanes' worth of cars.

With a Redis cache set to expire (TTL) every 30 seconds, the database is only queried when the cached value is missing or has expired — not on every single request:

Number of times the cache refreshes in 1 hour = 3600 / 30 = 120 times
So the database is queried only 120 times, not 180,000 times

That is roughly 1,500 times fewer database queries (180,000 ÷ 120 = 1,500), for the exact same 500 students refreshing at the exact same rate. We can also express this as a cache hit ratio — the fraction of requests that Redis answered directly without touching the database:

Hits = 180,000 - 120 = 179,880
Hit ratio = hits / total requests = 179,880 / 180,000 = 0.9993 = 99.93%

Only 0.07% of requests ever reach the database; the rest are served from RAM in a fraction of a millisecond. This is the actual mechanism behind why apps that get sudden bursts of identical traffic — a school portal on results day, a ticketing site during Tatkal, a cricket app during the last over of a close match — stay responsive instead of crashing.

Talking to Redis: Commands

Redis is controlled using simple text commands. You can try these yourself using the redis-cli tool that ships with Redis:

$ SET seat:12951:B4 "23"
OK
$ GET seat:12951:B4
"23"
$ EXPIRE seat:12951:B4 5
(integer) 1
$ TTL seat:12951:B4
(integer) 4
... 5 seconds pass ...
$ GET seat:12951:B4
(nil)

Trace through this line by line. SET stores the value "23" under the key seat:12951:B4. GET reads it straight back. EXPIRE tells Redis to automatically delete this key after 5 seconds, and Redis confirms with (integer) 1, meaning "yes, an expiry was successfully attached." TTL (time to live) asks Redis how many seconds are left before the key disappears — here it reports 4, because roughly a second has already passed. After the full 5 seconds elapse, the key is gone entirely, so GET returns (nil), Redis's way of saying "no value found."

Setting a value and its expiry in one atomic step (so there's never a moment where the key exists without an expiry) is done with SETEX:

$ SETEX seat:12951:B4 5 "23"
OK

Using Redis From Real Application Code

Here is the cache-aside pattern written as actual Python, using the popular redis-py library:

import redis
import time

# Connect to a Redis server running on the same machine, default port 6379
cache = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

def query_database(train_no, coach):
    time.sleep(0.2)          # simulate a slow, disk-based database lookup
    return "23"               # pretend the database reports 23 seats free

def get_seat_availability(train_no, coach):
    key = f"seats:{train_no}:{coach}"     # build a unique cache key
    cached_value = cache.get(key)          # Step 1: ask Redis first

    if cached_value is not None:            # Step 2: cache hit
        print("Served from Redis cache")
        return cached_value

    print("Cache miss -- querying database")  # Step 3: cache miss
    result = query_database(train_no, coach)    # slow path
    cache.setex(key, 5, result)                  # store it, expire in 5 sec
    return result

Trace through what happens on three back-to-back calls. First call, get_seat_availability("12951", "B4"): the key becomes "seats:12951:B4". Nothing is cached yet, so cache.get(key) returns Python's None. The if condition is false, so we fall through to the miss branch: query_database runs, sleeping for 0.2 real seconds before returning "23". Then cache.setex(key, 5, "23") stores that value in Redis with a 5-second expiry, and the function returns "23". Total time taken: about 200 milliseconds.

Second call, made 1 second later with the same train and coach: cache.get(key) now finds the value that was stored a second ago and returns the string "23" — not None. The if condition is true, so the function prints "Served from Redis cache" and returns immediately, without ever calling query_database or sleeping. Total time taken: well under a millisecond.

Third call, made 6 seconds after the first (past the 5-second TTL): Redis has already deleted the key on its own. cache.get(key) returns None again, so the function falls back into the miss branch, pays the 200 ms cost again, and re-stores a fresh value. This is exactly why we set a TTL rather than caching forever: the real seat count on the train genuinely changes as other people book tickets, so a cached answer that is too old becomes actively wrong, not just slightly stale.

Why Expiry (TTL) Matters: The Trade-Off Caching Introduces

A cache buys you speed, but it introduces a new problem that a plain database read never had: the value Redis hands back might not be the current truth at this exact instant. Choosing a TTL is choosing a trade-off between speed and freshness:

  • A very short TTL (say, 2 seconds) keeps the cached seat count almost perfectly accurate, but the database gets asked much more often, so you gain less speed benefit.
  • A very long TTL (say, 10 minutes) removes almost all database load, but for those 10 minutes, students might see a seat count that no longer matches reality — someone else booked the last seat two minutes ago, and the cache hasn't found out yet.

Choosing the right TTL depends entirely on how fast the underlying data actually changes and how much staleness a user can tolerate. A live train-seat counter needs a short TTL (seconds). A CBSE datesheet PDF link that won't change again this year could safely use a TTL of hours, or even be cached with no expiry at all, since the underlying value is effectively permanent. This decision — how stale is acceptable? — is one of the genuinely hard design questions in real backend systems, because getting it wrong either wastes the cache's benefit (TTL too short) or serves confidently wrong data to users (TTL too long).

Common Misconception: "Redis Replaces the Database"

A mistake many beginners make is assuming Redis is meant to replace a regular database like MySQL or PostgreSQL entirely, since it can store and retrieve data just like one. This is incorrect, and the reason matters: Redis keeps its data primarily in RAM, and RAM is volatile — if the Redis server restarts or crashes, data that wasn't specifically configured to be saved to disk is lost. A ticket-booking system's permanent record of who booked which seat cannot be allowed to vanish if a server reboots, so that record must live in a proper database with durable, disk-backed storage. Redis's usual job is to sit in front of that database as a temporary, disposable speed layer — if the entire Redis cache were wiped right now, the app would just experience a burst of cache misses and rebuild the cache from the database, slower for a little while but with no data actually lost. The database is the source of truth; Redis is a fast, forgetful assistant that remembers recent answers so the source of truth isn't hammered with repeat questions.

Where You've Already Benefited From This Idea

You have been using caching, without necessarily calling it that, every time you use a phone or computer. Your web browser caches images and page files it has already downloaded, so revisiting a site loads faster the second time. Your phone's network settings cache the numeric address behind a website name so it doesn't have to look it up again on every single request. Redis takes this same "remember instead of recompute" idea and turns it into a general-purpose, shareable tool that any backend application can plug in to protect its database from repeated, avoidable work.

Check Your Understanding

  1. In your own words, why is a cache hit so much faster than a cache miss, in terms of where the data physically comes from?
  2. In the cache-aside pattern, name the exact step at which data gets written into Redis, and explain why that step only happens on a miss, never on a hit.
  3. True or False, with a reason: "Once a value is stored in Redis, it will always be correct, no matter how long you wait before reading it."
  4. 1,000 devices poll a Redis-cached value every 2 seconds, continuously, for 10 minutes (600 seconds). The cache TTL is 20 seconds. (a) How many total requests are made? (b) How many times is the underlying database actually queried? (c) What is the cache hit ratio, as a percentage?
  5. Explain, using the RAM-vs-disk speed gap, why storing the cache in RAM rather than on a disk-based table is the whole point of Redis, not an incidental detail.

Answers: (1) A cache hit is answered directly from RAM, which is faster than a disk-based database read by several orders of magnitude, and it also skips re-running any expensive calculation or query entirely. (2) Data is written into Redis only in the miss branch, right after the slow database query returns — writing on every hit as well would be pointless since the value already matches what's stored, and would add unnecessary work to the fast path. (3) False — Redis only holds whatever was true at the moment it was written; if the real data changes afterward and no TTL has expired yet, the cached value becomes stale and wrong until it expires and is refreshed. (4) Total requests = 1000 x (600/2) = 300,000. Database queries = 600/20 = 30. Hit ratio = (300,000-30)/300,000 = 299,970/300,000 = 0.9999 = 99.99%. (5) Because RAM's speed (roughly 100 nanoseconds per access) versus disk's speed (roughly 100 microseconds for SSD, up to 10 milliseconds for older hard disks) is a difference of three to five orders of magnitude — if Redis stored its cache on disk instead of RAM, it would lose almost the entire reason for existing, since a disk-backed cache would be barely faster than the database it's supposed to protect.

Summary

  • A cache stores the answer to an expensive question so that repeated, identical questions can be answered instantly instead of recomputed.
  • RAM is faster than disk by several orders of magnitude (roughly 100 nanoseconds vs. 100 microseconds to 10 milliseconds); Redis exploits this gap by keeping cached data in RAM.
  • Redis is an in-memory, key-value store, running as its own shared server, offering O(1) average-time lookups through a hash table.
  • The cache-aside pattern: check Redis first; on a hit, answer immediately; on a miss, query the real database, store the result in Redis, then answer.
  • TTL (time-to-live) controls how long a cached value is trusted before it expires and must be refetched — a trade-off between speed (favoring long TTLs) and freshness (favoring short TTLs).
  • Redis complements a permanent database rather than replacing it; the database remains the durable source of truth, while Redis absorbs repeated read traffic.
  • Real Redis commands you can try: SET, GET, EXPIRE, TTL, and the combined SETEX.

Practice Exercises

Now it is time to practice! Complete these challenges to solidify your understanding:

  • Exercise 1: Write a short program that demonstrates the core concept from this chapter. Test it with at least 3 different inputs.
  • Exercise 2: Find a real-world example where redis: speed up your apps with caching is used in an Indian company (like TCS, Infosys, Flipkart, or ISRO). Write a paragraph explaining the connection.
  • Exercise 3: Create a mind-map connecting redis: speed up your apps with caching to at least 3 other topics you have studied.
← Mixture of Experts: Scaling Models EfficientlyCryptography: The Science of Secrets →

Found this useful? Share it!

📱 WhatsApp 🐦 Twitter 💼 LinkedIn