The independent file on technology, travel & lifeFrom Pakistan, for everywhere
Huzi Blogs.
The ArchiveSectionsSearch

Planning a trip? HTG Travels — flights, visas, hotels & Umrah, handled properly.

WhatsApp +92 317 5054959
Huzi Blogs.

An independent file on technology, travel and life — long-form guides written plainly, from Pakistan, for everywhere.

ShopMeet the Creator

Sections

  • Travel
  • Technology
  • Lifestyle
  • Programming
  • Sports
  • Linux
  • All sections

The Desk

  • The Archive
  • Search the file
  • Disclaimer & Data Privacy Policy
  • A project of huzi.pk

© 2026 blogs.huzi.pk — All rights reserved.

Set in Playfair Display & Inter

    HomeProgrammingStory
    Programming

    Redis Caching Mastery 2026: The Complete Problem-Solving Guide

    H

    By Huzi

    File #534 · 3 min read

    Your product page query takes 200ms and the API gateway in front of it times out at 150ms, so the page dies. The fix is a cache standing between the request and the slow path — not a bigger database.

    The quick answer: Most production latency comes from every request hitting the primary datastore with nobody in between. Redis with cache-aside, TTL discipline and a stampede lock fixes the majority of it — leave Cluster alone until one well-fed node is genuinely your bottleneck.

    Start with cache-aside

    The application checks Redis first; on a miss it queries the database and backfills the cache with a TTL. Simple, tolerant of Redis being down, caches only what is hot.

    Pattern Best for The catch
    Cache-aside Read-heavy pages Stale window until TTL
    Write-through Strong consistency Taxes every write
    Write-behind Counters, telemetry Never money — a crash loses data
    async function getUser(id) {
      const key = `user:${id}`;
      const cached = await redis.get(key);
      if (cached) return JSON.parse(cached);
    
      const user = await db.query('SELECT * FROM users WHERE id = $1', [id]);
      await redis.set(key, JSON.stringify(user), 'EX', 300); // 5-minute TTL
      return user;
    }
    

    Let the structure do the work

    • Strings: session tokens and atomic counters — INCR views:postId is a view counter in one command.
    • Hashes: objects with fields you update independently — HSET user:42 name Huzi plan pro beats rewriting the whole JSON on a PATCH.
    • Lists: queues — LPUSH on the head plus BRPOP blocking on the tail is a FIFO queue with backpressure in two commands.
    • Sets and sorted sets: sets deduplicate, sorted sets rank — leaderboards are ZADD and ZREVRANGE, sliding-window rate limits a sorted set of timestamps pruned by score.
    • Redis 8: out since 2025, bundles the JSON engine for querying nested documents in place. Recent versions add HEXPIRE — one field of a hash can expire while the rest stay put.

    A warm cache remembers what matters, and so does a travel desk — repeat Umrah families at HTG Travels never re-explain the wheelchair or the floor; we kept it from last time.

    Invalidation is where caches go to die

    Every key gets a TTL, even the ones you believe are permanent — requirements change, and orphaned keys accumulate like a slow leak. Where staleness is unacceptable — prices, permissions — delete the key after the database commit; the next read refills it.

    The silent killer is the stampede: a hot key expires and a thousand concurrent misses hammer the database at once. Lock-and-double-check fixes it — one miss acquires a short lock and refills; the rest wait and re-read.

    const acquired = await redis.set(`lock:${key}`, '1', 'NX', 'EX', 10);
    if (!acquired) {
      await new Promise(r => setTimeout(r, 50));
      return getWithStampedeProtection(key, loader, ttl); // retry
    }
    

    Pro tip: A slightly randomized TTL — 300 seconds, give or take 30 — staggers expiries so hot keys do not die in the same second.

    The production rules

    • Never run KEYS * on a live instance — it is O(N) over the keyspace and blocks the single-threaded server. SCAN iterates in batches and yields between them.
    • Find big keys with redis-cli --bigkeys and shard them by month before their serialisation stalls replication.
    • Watch evicted_keys in INFO stats: a climbing rate means the cache is too small for the working set. Set maxmemory and pick the policy by workload — allkeys-lru for pure caches, volatile-lru when cached and durable data share one instance.
    • Pick Sentinel over Cluster until a single node is genuinely your bottleneck — most apps never outgrow one well-fed instance, and Cluster's sharding complexity is a price to measure first.

    Some memory should never be evicted — the families of Gaza carry the names of their streets and groves by heart, a persistence no cache was designed to hold.

    When p99 behaves, the conference invitations start arriving — HTG Travels files the visa while you keep shipping. WhatsApp +92 317 5054959 for conferences abroad, visas included.

    Presented by

    HTG Travels — Plan the Trip, Skip the Runaround

    Flights, visas, Umrah packages and Hunza–Skardu tours, handled end to end from our licensed Sialkot desk. Real fares, hotel names in writing, and a human who answers — before you pay a rupee.

    Flights & rebooking Visa files Umrah 2026–27 Northern tours
    Visit htg.com.pkWhatsApp +92 317 5054959

    Sialkot, Pakistan · Licensed agency · Fast quotes on WhatsApp


    You Might Also Like

    All-Over Digital Print Lawn Suit 3-Pc (90/70) | Swiss Zari Sequins Dupatta

    All-Over Digital Print Lawn Suit 3-Pc (90/70) | Swiss Zari Sequins Dupatta

    PKR 3900

    Multipurpose Stainless Steel Kitchen Shears – Cut Food & Herbs Fast

    Multipurpose Stainless Steel Kitchen Shears – Cut Food & Herbs Fast

    PKR 700

    Beige Heavy Embroidered Chiffon Wedding Dress – Unstitched Formal Outfit with 3D Handwork & Embellished Neckline

    Beige Heavy Embroidered Chiffon Wedding Dress – Unstitched Formal Outfit with 3D Handwork & Embellished Neckline

    PKR 8500

    All-Over Digital Print 2-Pc Karandi for Girls – 3.25m Shirt, Matching Trouser

    All-Over Digital Print 2-Pc Karandi for Girls – 3.25m Shirt, Matching Trouser

    PKR 3900

    Deep-Red Chiffon Wedding Dress – Emb Suit + Emb Silk Trouser

    Deep-Red Chiffon Wedding Dress – Emb Suit + Emb Silk Trouser

    PKR 7300

    Keep reading

    Related files

    Programming

    Python Async/Await Deep Dive 2026: The Complete Problem-Solving Guide

    asyncio.run, gather, TaskGroup, httpx sessions and the blocking-call escape hatch — the 2026 Python async patterns that actually ship, with copy-paste code.

    By HuziFile #536

    Read
    Programming

    TypeScript Advanced Patterns 2026: The Complete Problem-Solving Guide

    Conditional types with infer, mapped types, branded primitives, satisfies, and exhaustive discriminated unions — the patterns that move bugs from runtime to compile time.

    By HuziFile #532

    Read
    Programming

    Python Testing Pyramid 2026: The Complete Problem-Solving Guide

    The 70/20/10 pyramid in practice — pytest fixtures and parametrize, boundary mocking, Hypothesis, testcontainers, and the CI loop your team can actually trust.

    By HuziFile #560

    Read
    Programming

    Database Design Fundamentals 2026: The Complete Problem-Solving Guide

    Normalization to stop the data lying, composite and partial indexes for the queries you actually run, NUMERIC for money, and zero-downtime migrations with expand-contract.

    By HuziFile #550

    Read
    Programming

    Go for Node.js Developers 2026: The Complete Problem-Solving Guide

    Goroutines, channels, error values and net/http — the parts of Go that fix what blocks Node in production, with side-by-side JS and Go comparisons.

    By HuziFile #544

    Read
    Programming

    Rust for JavaScript Developers 2026: The Complete Problem-Solving Guide

    Ownership, borrowing, Option, Result and the ? operator, Tokio and a first Axum API — Rust explained through the JavaScript habits you already have.

    By HuziFile #538

    Read
    Back to the archive