Software Engineer Encyclopedia
0%
Domain 04 · Database Engineering & Data Management · Topic 4.9

Caching في ASP.NET Core: من Cache-Aside إلى الاتساق والأداء

Caching — Deep Practical Guide for .NET Applications

مرجع caching شامل: hit/miss، in-memory/distributed، cache-aside، TTL، invalidation، stampede، consistency، HybridCache، output/HTTP caching، warming وmetrics.

  • Intermediate
  • ~16 min read
  • 12 sections
  • 13 code examples
  • 1 diagrams
  • 5 questions
  • Priority L1 · Important
  • .NET 10 · ASP.NET Core 10 · Redis 8

المتطلبات قبل ما تبدأ

C# وأساسيات ASP.NET Core. معرفة سابقة بـ SQL مفيدة لكن مش شرط.

مستوى التعمق المطلوب

DEEP PRACTICALUnderstand which data can become stale and how to avoid overwhelming the database.

01

ليه بنعمل Cache؟

Latency, throughput and repeated work
Deep dive

Cache تخزن نتيجة قابلة لإعادة الاستخدام بالقرب من المستهلك لتقليل latency أو الضغط على source of truth. الفائدة مش «Redis أسرع من SQL» بشكل مطلق؛ الفائدة تظهر لما نفس البيانات تُقرأ كثيرًا، وتتغير بمعدل أقل، وتكلفة إعادة حسابها/قراءتها عالية نسبيًا. Cache تضيف نسخة أخرى من البيانات، وبالتالي تضيف مشكلة freshness و invalidation و memory limits و failure modes.

Cache Hit يعني key موجود وصالح، وCache Miss يعني لازم نرجع للمصدر. Hit ratio وحده لا يكفي: 99% hit على بيانات صغيرة قد لا يساوي شيئًا، و80% hit على query مكلفة قد يكون ممتازًا. قِس latency saved و DB load و cache operation cost و payload size.

لا تعمل cache قبل تحديد bottleneck. لو endpoint بطيء بسبب N+1 أو missing index، cache قد تخفي المشكلة مؤقتًا وتضيف invalidation bug. حسّن query أولًا، ثم cache عندما تثبت أن reuse يبرر التعقيد.

02

In-Memory vs Distributed Cache

Where does cached state live?
Deep dive

In-memory cache مثل IMemoryCache سريعة جدًا ولا تحتاج network، لكنها خاصة بكل process وتختفي مع restart. لو عندك 4 API replicas، كل واحدة لها cache مختلفة. مناسبة للبيانات المحلية الصغيرة أو per-instance metadata، مع limits واضحة.

Distributed cache مثل Redis تشاركها instances، وتبقى مستقلة عن دورة حياة API process، لكنها تضيف network hop و serialization و dependency تشغيلية. IDistributedCache abstraction بسيطة للتعامل مع byte payloads، بينما Redis client المباشر يتيح sorted sets/atomic commands/streams.

C#Memory cache with explicit size and expiration
builder.Services.AddMemoryCache(options =>
{
    options.SizeLimit = 10_000; // application-defined size units
    options.CompactionPercentage = 0.20;
});

public sealed class ProductLookup(IMemoryCache cache, AppDbContext db)
{
    public Task<ProductDto?> GetAsync(int id, CancellationToken ct) =>
        cache.GetOrCreateAsync($"product:{id}", async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(3);
            entry.Size = 1;
            return await db.Products.AsNoTracking()
                .Where(p => p.Id == id)
                .Select(p => new ProductDto(p.Id, p.Name, p.Price))
                .SingleOrDefaultAsync(ct);
        });
}

Size units ليست bytes تلقائيًا؛ أنت تحدد معنى size وتلتزم به في كل entry عند استخدام SizeLimit. لا تضبط global size limit على shared IMemoryCache بدون التأكد أن كل library تضيف entries متوافقة مع سياسة الحجم.

Redis Down: Fail Open ولا Fail Closed؟

لو cache unavailable، هل request ترجع DB مباشرة؟ لقراءة catalog غالبًا fail-open إلى DB مع concurrency protection. لبيانات authorization أو quota أو idempotency، fallback قد يغير security/correctness؛ ربما fail-closed أو use a durable source. القرار حسب semantic role للـ cache: performance optimization أم جزء من correctness state.

لو كل replicas تعمل fallback على DB في نفس الوقت، outage في Redis قد يسبب database overload (thundering herd). أضف circuit breaker، bounded concurrency، request queue/503 عند الضغط، و stale local cache لو مقبول. لا تلتقط كل Exception وتسكت؛ صنّف Redis timeout vs serialization bug vs configuration failure.

C#Fallback policy sketch
try
{
    return await cache.GetStringAsync(key, ct);
}
catch (RedisException ex)
{
    logger.LogWarning(ex, "Cache unavailable; falling back to source");
    // Only safe for this read path; enforce DB concurrency limits.
    return await LoadFromDatabaseAsync(ct);
}

الكود sketch؛ لا تلتقط exception عام وتحوّل كل failure إلى DB fallback. Serialization error قد يدل على incompatible cache schema ويحتاج alert/eviction/version bump. وعمليات writes/authorization لا تستخدم نفس fallback policy دون threat review.

03

Cache-Aside: النمط الأساسي

Read-through application flow
Deep dive

التدفق: ابنِ key → اقرأ cache → لو hit أرجع value → لو miss اقرأ DB → حوّل إلى DTO → اكتب cache مع expiration → أرجع النتيجة. Cache لا تصبح source of truth؛ DB تظل المرجع. خزن DTO مستقرة وليس tracked EF entity، واعمل versioning للـ key عند تغيير serialization contract.

C#Distributed cache-aside
public sealed class ProductQueries(AppDbContext db, IDistributedCache cache)
{
    public async Task<ProductDto?> GetAsync(int id, CancellationToken ct)
    {
        var key = $"product:v2:{id}";
        var cached = await cache.GetStringAsync(key, ct);
        if (cached is not null)
            return JsonSerializer.Deserialize<ProductDto>(cached);

        var dto = await db.Products.AsNoTracking()
            .Where(p => p.Id == id)
            .Select(p => new ProductDto(p.Id, p.Name, p.Price))
            .SingleOrDefaultAsync(ct);

        if (dto is not null)
        {
            var options = new DistributedCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
            await cache.SetStringAsync(key, JsonSerializer.Serialize(dto), options, ct);
        }
        return dto;
    }
}

الكود التوضيحي يحتاج handling لـ serialization failure و cache outage. قرر: هل cache failure تسمح بالـ DB fallback؟ غالبًا نعم لقراءة عادية، لكن لو DB نفسها overloaded قد تحتاج circuit breaker/degraded response. لا تجعل Redis outage يؤدي إلى آلاف concurrent DB calls.

Cache Key Design و Tenant Isolation

لو cache تخزن بيانات متعددة tenants، key يجب تتضمن tenant scope أو user scope حسب ownership. key مثل order:42 قد تتصادم أو تسمح بإرجاع بيانات tenant آخر إذا IDs ليست global. استخدم key builder مركزيًا يضمن namespace/version/tenant. لا تقبل cache key كاملة من request؛ ابنها server-side من identifiers بعد authorization.

Cache poisoning يحدث عندما attacker يقدر يؤثر في value المخزنة أو vary dimension، ثم مستخدم آخر يحصل عليها. راجع Host/Origin/Accept-Language/currency/query parameters التي تؤثر في representation، وضمنها في key أو امنع caching. لا تخزن authenticated response تحت public key. serialization payload يجب تكون typed/versioned ولا deserialize arbitrary CLR types.

Key Design و Negative Caching و Cache Security

اجعل cache key يضم كل dimension تؤثر على النتيجة: tenant، user/permission scope عند اللزوم، locale، version، filters. Key ناقص قد يعرض بيانات tenant لمستخدم آخر، وهي ثغرة أمنية وليست bug أداء. لا تخزن response شخصية في shared cache بلا partition واضح.

Negative caching يخزن “غير موجود” لفترة قصيرة لتقليل repeated misses، لكنه يحتاج TTL أقل غالبًا حتى لا يخفي إنشاء record جديد. حدّد حجم payload، وسياسة eviction، وحدود الذاكرة. لا تستخدم cache كمصدر الحقيقة إلا لو صممت النظام صراحةً على ذلك.

C#Practical engineering example
string key = $"tenant:{tenantId}:product:v2:{productId}";

// Negative caching should be short and explicit:
if (product is null)
{
    await cache.SetStringAsync(
        $"{key}:missing", "1",
        new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30)
        }, ct);
}

استخدم metrics مثل hit ratio و miss rate و evictions و latency وحجم payload. Hit ratio مرتفع لا يعني نجاحًا إذا كانت البيانات stale أو keys قليلة الاستخدام تشغل الذاكرة. اختبر invalidation عند update/delete، وراقب cache outage؛ التطبيق يجب أن يملك fallback strategy معقولة بدل الانهيار الكامل.

Worked Example: Product Catalog Cache

افترض catalog public يتغير عدة مرات في اليوم، وقراءة المنتجات كثيفة. key: catalog:v4:category:{id}:page:{cursor}:currency:{currency}. TTL 2–5 دقائق مع jitter. عند تعديل product، outbox event تبطل product detail key و category/list versions. لو Redis وقع، endpoint قد تستخدم local fallback bounded أو 503 عند DB saturation. لا تخزن personalized prices في نفس public key.

Acceptance criteria: response لا تتجاوز 100 item، كل cache entry versioned، tenant-specific price خارج public cache، invalidation lag أقل من business tolerance، hit/miss metrics موجودة، والـ fallback لا يسبب DB overload. هذا يحول caching من إضافة Redis إلى design قابل للقياس.

04

TTL و Absolute/Sliding Expiration

Freshness is a business decision
Deep dive

Absolute expiration تنهي entry في وقت محدد مهما تم قراءتها. Sliding expiration تمدد عمر entry مع الاستخدام، وقد تجعل key ساخنة تعيش طويلًا جدًا؛ غالبًا تجمع معها absolute cap. TTL يجب أن يعكس stale tolerance، update frequency، source cost، والـ invalidation guarantees.

أضف jitter عشوائيًا صغيرًا إلى TTL لتجنب انتهاء آلاف keys في نفس اللحظة. لا تستخدم نفس TTL لكل domain: product catalog قد يتحمل دقائق، exchange rate قد يحتاج freshness أقصر، و permission/security data قد تحتاج invalidation فوري أو لا تُخزن في cache مشتركة أصلًا.

C#Expiration with jitter
var jitterSeconds = Random.Shared.Next(0, 31);
var ttl = TimeSpan.FromMinutes(5) + TimeSpan.FromSeconds(jitterSeconds);
var options = new DistributedCacheEntryOptions()
    .SetAbsoluteExpiration(ttl);
await cache.SetStringAsync(key, payload, options, ct);

في tests لا تعتمد على sleep طويل؛ استخدم clock abstraction أو test cache/fake time provider إن كان ذلك مناسبًا. اختبر الحدود: entry قبل expiry، بعد expiry، sliding refresh، والـ absolute cap.

05

Cache Invalidation و Consistency

When source data changes
Deep dive

أصعب سؤال في caching: لما البيانات تتغير، إزاي النسخ المخزنة تتحدث؟ خياراتك: TTL فقط (eventual staleness bounded تقريبًا)، explicit eviction بعد write، event-driven invalidation، versioned keys، أو write-through. لا توجد استراتيجية واحدة تناسب كل البيانات.

لو عملت update في DB ثم cache remove وفشل remove، entry القديمة ستظل موجودة حتى expiry. لو مسحت cache قبل DB update وفشل DB، قد تعيد تحميل القيمة القديمة. ترتيب العملية والـ retry والـ event delivery كلها مهمة. في الأنظمة المهمة، transactional outbox يضمن تسجيل invalidation event مع transaction DB، ثم dispatcher ينشره بشكل retryable.

C#Write then invalidate (simple policy)
public async Task UpdatePriceAsync(int id, decimal price, CancellationToken ct)
{
    var product = await db.Products.SingleAsync(x => x.Id == id, ct);
    product.Price = price;
    await db.SaveChangesAsync(ct);

    await cache.RemoveAsync($"product:v2:{id}", ct);
}

ده مناسب كبداية لكنه ليس atomic بين SQL و Redis. لو invalidation failure لا يجوز أن يستمر stale data، أضف outbox/event retry أو version key. لا تكتب DB و Redis في distributed transaction افتراضية؛ صمم consistency model واعرف stale window المقبولة.

Race Conditions بين DB Update و Cache Invalidation

سيناريو خطير: Request A تقرأ cache miss وتبدأ تحميل القيمة القديمة من DB. Request B تحدث DB ثم تمسح cache. بعد ذلك A تكتب القيمة القديمة في cache بعد عملية المسح؛ فتعود stale value وتظل حتى TTL. ترتيب DB update ثم remove وحده لا يمنع هذا race.

حلول ممكنة حسب الحساسية: versioned keys مرتبطة ب data version، invalidation event مع monotonic version، short TTL مع stale tolerance، per-key coordination، أو cache write مشروط بأن version لم تتغير. لا يوجد حل مجاني؛ distributed locking قد يزيد latency ويحتاج failure handling.

TextVersioned key concept
product:42:version:17  -> cached representation

Database update increments Product.CacheVersion to 18.
Readers now request product:42:version:18.
Old version 17 becomes unreachable and expires naturally.

Versioned keys تقلل الاعتماد على delete الدقيق لكنها تحتاج معرفة version الحالية بسرعة، وقد تتطلب key pointer/current version. لو version نفسها cached، راجع consistency of pointer. استخدمها عندما stale overwrite risk مهم والـ invalidation معقد.

Event-Driven Invalidation مع Outbox

لو cache invalidation event مهمة، أضف outbox row في نفس transaction مع business update. Dispatcher يقرأ pending events ويرسلها إلى handler يمسح keys أو يغير version. لو dispatcher crash بعد publish وقبل mark، event تتكرر؛ handler لازم تكون idempotent. لو cache delete فشل، retry لاحقًا. راقب event age/invalidation lag.

C#Outbox event handler invalidates cache
public sealed class ProductChangedHandler(
    IDistributedCache cache, ILogger<ProductChangedHandler> logger)
{
    public async Task Handle(ProductChanged message, CancellationToken ct)
    {
        await cache.RemoveAsync($"product:v3:{message.ProductId}", ct);
        logger.LogInformation("Invalidated product cache for {ProductId}",
            message.ProductId);
    }
}

لو event تحتوي tenant/product IDs، تأكد من source و authorization داخل event pipeline. لا تجعل invalidation event تعتمد على client-supplied IDs بلا validation. Outbox لا يضمن cache update لحظيًا؛ consistency model ما زالت eventual.

Cache Correctness: Staleness و Invalidation و Stampede

Request Build scoped key Cache Hit or miss Database Load on miss Cache Set TTL + return
Cache-aside read flow

الكاش يضيف نسخة ثانية من البيانات، وبالتالي يضيف مشكلة اتساق. في Cache-Aside، التطبيق يقرأ cache؛ عند miss يقرأ source of truth ثم يملأ cache. عند update، غالبًا يحدث database أولًا ثم invalidates key. لو عكست الترتيب قد تعيد عملية قراءة متزامنة قيمة قديمة إلى الكاش بعد invalidation.

TTL يحد أقصى عمر تقريبي للبيانات لكنه لا يضمن consistency فورية. اختر TTL حسب business tolerance، واستخدم versioned keys أو invalidation events عند الحاجة. Cache stampede يحدث عندما تنتهي صلاحية key مشهور فيتجه عدد كبير من الطلبات للمصدر في وقت واحد؛ الحلول تشمل single-flight per key، jitter، stale-while-revalidate، و refresh-ahead.

C#Practical engineering example
// Cache-aside with per-key request coalescing (simplified)
private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new();

public async Task<ProductDto?> GetAsync(int id, CancellationToken ct)
{
    var key = $"product:{id}";
    var cached = await cache.GetStringAsync(key, ct);
    if (cached is not null) return JsonSerializer.Deserialize<ProductDto>(cached);

    var gate = _locks.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
    await gate.WaitAsync(ct);
    try
    {
        cached = await cache.GetStringAsync(key, ct); // double-check
        if (cached is not null) return JsonSerializer.Deserialize<ProductDto>(cached);
        var product = await repository.FindAsync(id, ct);
        if (product is null) return null;
        var json = JsonSerializer.Serialize(product);
        await cache.SetStringAsync(key, json,
            new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) }, ct);
        return product;
    }
    finally { gate.Release(); }
}

هذا المثال يوضح الفكرة لكنه يحتاج cleanup لمدخلات _locks أو استخدام keyed-lock library في تطبيق طويل العمر حتى لا تكبر dictionary بلا حدود. في multi-instance deployment، القفل المحلي يمنع stampede داخل process واحدة فقط؛ استخدم distributed coordination أو stale serving إذا كانت المشكلة تستحق التعقيد.

06

Cache Stampede و Penetration و Breakdown

Protect the origin under pressure
Deep dive

Stampede: key شائعة تنتهي ويبدأ عدد كبير من requests بتحميلها. Penetration: requests لمفاتيح غير موجودة تتكرر وتذهب للمصدر. Breakdown/hot key: عنصر شديد الطلب يصبح miss أو مصدره غير متاح فيتحول إلى bottleneck. الأدوات: jitter، single-flight، refresh-ahead، stale-while-revalidate، negative caching ب TTL قصير، request coalescing، rate limiting و bulkheads.

Single-flight يجمع عدة requests لنفس key في load واحد داخل process. ده لا يمنع stampede بين replicas. Distributed lock قد يساعد لكنه يحتاج lease/token/fencing وفهم failure modes؛ أحيانًا stale data مؤقتًا أكثر أمانًا وأبسط.

C#Negative caching with short TTL
var missingKey = $"product-missing:v1:{id}";
var cachedMissing = await cache.GetStringAsync(missingKey, ct);
if (cachedMissing is not null) return null;

var product = await LoadProductAsync(id, ct);
if (product is null)
{
    await cache.SetStringAsync(missingKey, "1",
        new DistributedCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromSeconds(20)), ct);
    return null;
}

لا تستخدم negative cache لفترات طويلة؛ resource قد يُنشأ بعد miss. عند create احذف missing key، أو استخدم key namespace/version يجعل الإنشاء invalidates absence cache.

Cache Stampede و Dogpile و Invalidation Strategies

لو key شائع انتهى TTL في نفس اللحظة لآلاف requests، كلهم قد يذهبون إلى database؛ هذا cache stampede. حلول: per-key single-flight داخل process، distributed lease بحذر، TTL jitter، stale-while-revalidate، pre-warming، أو request coalescing. distributed lock ليس ضمانًا مطلقًا؛ lease expiry و network partitions قد يسمحان لأكثر من owner، لذلك side effect يجب يكون idempotent أو fencing-token protected.

Invalidation أصعب من caching. Cache-aside يكتب database ثم يمسح key؛ لو فشل delete قد يبقى stale. Write-through يحدث cache مع source وفق consistency contract. Versioned keys أو event-driven invalidation تساعد، لكنها تحتاج معالجة duplicate/out-of-order events. ضع maximum TTL و fallback behavior، ولا تخزن authorization decisions أو tenant data بمفتاح لا يحتوي tenant scope.

07

HybridCache: L1 + L2

Two-level caching in modern .NET
Practical

HybridCache يوفر abstraction تجمع local in-process cache (L1) مع distributed cache (L2) عند إعدادها، ويقدم stampede protection ضمن تصميمه. L1 تقلل network hops، و L2 تشارك البيانات بين instances. لازم تفهم invalidation semantics بين مستويات cache والـ tag invalidation والـ serialization.

C#HybridCache registration and usage
builder.Services.AddHybridCache(options =>
{
    options.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(5),
        LocalCacheExpiration = TimeSpan.FromSeconds(30)
    };
});

public sealed class ProductReader(HybridCache cache, AppDbContext db)
{
    public ValueTask<ProductDto?> GetAsync(int id, CancellationToken ct) =>
        cache.GetOrCreateAsync(
            $"product:v3:{id}",
            async token => await db.Products.AsNoTracking()
                .Where(x => x.Id == id)
                .Select(x => new ProductDto(x.Id, x.Name, x.Price))
                .SingleOrDefaultAsync(token),
            cancellationToken: ct);
}

راجع package/framework availability والـ provider configuration للإصدار المستهدف، ولا تفترض أن وجود HybridCache يلغي الحاجة إلى key design و TTL و invalidation و metrics. لو تستخدم tags أو remove، اختبر أثرها على كل instances ومستوى L1/L2.

08

Output Caching و HTTP Caching و ETag

Cache whole responses safely
Deep dive

Output caching في ASP.NET Core يخزن response الناتج عن endpoint وفق policy server-side، ويمكنه vary by query/header وغيرها. HTTP caching يعتمد على browser/proxy/CDN directives مثل Cache-Control و ETag و Last-Modified. الفرق أن output cache قرار server، بينما HTTP cache يحدد سلوك clients/intermediaries أيضًا.

C#Output cache policy
builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("PublicCatalog", policy => policy
        .Expire(TimeSpan.FromSeconds(30))
        .SetVaryByQuery("category", "page"));
});

app.UseOutputCache();
app.MapGet("/catalog", GetCatalog).CacheOutput("PublicCatalog");

لا تعمل cache ل response شخصية/حساسة في policy عامة. راجع vary dimensions: tenant، user، language، currency، authorization scope. نسيان vary dimension قد يسبب data leakage بين users. لا تعتمد على cache key implicit غير مفهوم؛ وثّق policy وامنع caching للـ endpoints الحساسة.

HTTPHTTP cache headers
Cache-Control: public, max-age=60, stale-while-revalidate=30
ETag: "catalog-v42"

If-None-Match: "catalog-v42"

ETag يسمح للعميل يطلب revalidation؛ لو representation لم تتغير، السيرفر يرد 304 Not Modified. لا تضع public على response تحتوي user-specific information. للبيانات الخاصة استخدم policy مناسبة مثل private/no-store حسب sensitivity.

09

Cache Warming و Eviction و Memory Limits

Lifecycle and capacity planning
Deep dive

Cache warming يحمّل hot keys قبل peak traffic أو بعد deployment، لكنه قد يضغط على DB لو بدأ كل replica تسخن نفس البيانات. اعمل batch/rate limit، وراقب source load. لا تسخن كل البيانات؛ ركز على hot set المثبتة بال metrics.

Eviction policies مثل LRU/LFU/size-based تحدد ما الذي يخرج عند ضغط الذاكرة. في IMemoryCache، حدد size/expiration وراقب process memory. في Redis، اختر maxmemory policy مناسبة: allkeys-lru، volatile-ttl وغيرها وفق key TTL distribution. لا تعتمد على eviction policy كبديل لتحديد حجم payload و TTL.

راقب object graph serialization size، large strings، duplicate cache entries، cardinality العالية في keys، والـ per-tenant fairness. cache key من user input غير محدود قد يصنع memory exhaustion. ضع limits على key count/payload وراجع keys ذات high churn.

10

Metrics: إزاي تعرف إن الـ Cache بتفيد؟

Measure outcomes, not just hit ratio
Practical

قِس hit/miss count، hit ratio، cache operation latency، DB query count/latency، payload bytes، evictions، memory usage، key cardinality، stampede/coalesced load count، serialization failures، invalidation lag، و stale response incidents. افصل metrics حسب cache region/operation من غير cardinality عالية في labels.

قارن endpoint p50/p95/p99 قبل وبعد cache، وعدد DB calls تحت load. لا تعتبر ارتفاع hit ratio نجاحًا لو p99 زاد بسبب Redis bottleneck أو serialization. أضف tracing spans حول cache get/set و DB fallback لتعرف path لكل request.

Observability: Trace Cache Hit و Miss في Request

أضف tracing span لكل cache operation مع attribute محدود مثل cache region و hit/miss، ثم span لـ DB fallback. لا تضع full cache key أو user ID كـ high-cardinality metric label. استخدم structured logs مع key hash أو entity type عند الحاجة. قارن p95 latency للـ hit path والـ miss path، وراقب cache server latency منفصلًا عن app serialization time.

Alert على sudden hit-ratio drop، eviction spike، memory near maxmemory، high command latency، Redis connection churn، DB fallback surge، invalidation lag و stale data incidents. راقب per-region حتى لا تخفي region سيئة داخل global average.

قياس Cache: Hit Ratio لا تكفي

راقب hit/miss ratio، p95 cache latency، origin database QPS، eviction rate، memory usage، stale response age، refresh failures، و stampede events. Hit ratio مرتفعة قد تكون سيئة لو cached data قديمة أو hit على keys منخفضة القيمة. قس أثر cache على end-to-end latency والـ database load.

اختبر cache unavailable، Redis timeout، malformed serialization، schema version change، eviction، cold start، و concurrent miss. حدد fail-open/fail-closed لكل use case: catalog قد يرجع source مباشرة، بينما authorization cache قد يحتاج fail closed أو revalidate. لا تجعل cache failure يسبب retry storm على database؛ استخدم concurrency limits و fallback throttling.

11

إمتى ما تعملش Cache؟

Avoid caching the wrong data
Practical

تجنب cache عندما البيانات تتغير باستمرار ولا تتحمل stale reads، أو query رخيصة جدًا والـ serialization/network أغلى، أو dataset أكبر من memory المتاحة، أو key cardinality عالية بلا reuse، أو invalidation أعقد من قراءة المصدر. لا تخزن authorization decisions طويلة العمر بلا invalidation، ولا تخزن secrets أو بيانات حساسة في cache مشتركة بلا threat model واضح.

قرار caching لازم يحدد: source of truth، stale tolerance، TTL، invalidation trigger، outage behavior، capacity، metrics، و owner. لو مش قادر تجاوب عنهم، ابدأ بقياس source query وتحسينها قبل إضافة cache.

اختبار Cache Correctness

اختبر hit/miss، expiration، sliding behavior، serialization version mismatch، cache outage، DB fallback، invalidation بعد update، create بعد negative cache، tenant separation، stampede coalescing و hot-key behavior. اختبر إن user A لا يستطيع الحصول على cache value user B بسبب key collision أو missing vary dimension.

استخدم fake cache/clock في unit tests للـ orchestration، و Redis Testcontainer integration tests للـ atomic commands/serialization/TTL semantics. لا تستخدم in-memory dictionary لإثبات Redis cluster/hash slot behavior. performance tests تقيس hit latency/miss latency/DB load تحت concurrency، ولا تعتمد على single-request benchmark.

12

اختبر فهمك

Knowledge check
Practical
هل 100% hit ratio هدف دائم؟
لا؛ المهم أثر cache على latency والحمل والتكلفة، مع freshness و memory trade-offs.
ما الخطر في Output Cache ل endpoint شخصية؟
قد تُعاد response مستخدم إلى مستخدم آخر إذا لم تتضمن key/vary policy هوية أو scope مناسبة، أو إذا cache كانت عامة.
لماذا TTL jitter مفيد؟
يقلل انتهاء عدد كبير من keys في نفس اللحظة، وبالتالي يقلل احتمالية stampede.
هل invalidation بعد SaveChanges ذرية مع SQL transaction؟
لا؛ Redis/Distributed Cache ليست ضمن transaction SQL تلقائيًا. استخدم outbox أو versioning إذا كانت الضمانات مهمة.
متى لا تستخدم cache؟
عندما لا يوجد reuse حقيقي، أو stale data غير مقبولة، أو cache overhead أكبر من source cost، أو لا توجد سياسة invalidation/limits واضحة.
↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خريطة التغطية: 19 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapWhy Caching Matters§01
RoadmapCache Hit vs Cache Miss§01
RoadmapIn-Memory vs Distributed Cache§01
RoadmapCache-Aside Pattern§03
RoadmapTTL§03
RoadmapCache Invalidation§03
RoadmapCache Stampede§03
RoadmapCache Consistency§03
RoadmapKey Design§03
RoadmapSerialization§03
RoadmapMemory Limits§02
RoadmapEviction Policies§02
RoadmapCache Metrics§02
RoadmapWhen Not to Cache§02
SuggestedHybridCache (L1 + L2)§03
SuggestedOutput caching and response caching§03
SuggestedHTTP caching: ETag, Cache-Control, CDN§03
SuggestedCache warming and negative caching§03
SuggestedHit-ratio dashboards§03

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس