Video tayyorlanmoqda

Strong Junior 🏗️ System design

Bazada yo'q ID'lar bo'yicha ko'p so'rov kelsa, cache nega yordam bermaydi va nima qilasiz?

Bu cache penetration: yo'q kalit cache'ga hech qachon tushmaydi, shuning uchun har so'rov to'g'ridan-to'g'ri DB'ga boradi. Yechim — "yo'q" javobini ham qisqa TTL bilan cache qilish, ID formatini tekshirish, kerak bo'lsa Bloom filter.

📖 Javob

Cache-aside'da cache faqat topilgan qiymatni saqlaydi. Kimdir /products/999999999, /products/999999998... deb skript yurgizsa, har so'rov miss, har miss — DB'ga so'rov. Cache bor, lekin DB bu trafikni to'liq ko'taradi. Bu bot ham, front'dagi bug ham bo'lishi mumkin.

Eng oddiy yechim — bo'sh natijani ham cache qilish:

public Optional<Product> find(long id) {
    String key = "product:" + id;
    String cached = redis.opsForValue().get(key);
    if ("NULL".equals(cached)) return Optional.empty();   // ilgari ham yo'q edi
    if (cached != null) return Optional.of(fromJson(cached));

    Optional<Product> p = repo.findById(id);
    if (p.isPresent()) {
        redis.opsForValue().set(key, toJson(p.get()), Duration.ofMinutes(10));
    } else {
        redis.opsForValue().set(key, "NULL", Duration.ofSeconds(60)); // qisqa TTL
    }
    return p;
}

TTL qisqa bo'lishi shart: mahsulot keyinroq yaratilsa, foydalanuvchi uni bir daqiqadan ortiq "yo'q" deb ko'rmasin.

Qo'shimcha himoya:

  • ID'ni oldindan tekshirish — manfiy yoki juda katta raqam DB'gacha bormasin;
  • bitta IP'dan keladigan ko'p 404 ga rate limit;
  • kalitlar juda ko'p bo'lsa, Bloom filter: "bu ID aniq yo'q" deb DB'ga bormasdan javob beradi.