شعار Backend Caching Strategies

Backend Caching Strategies

المجتمع
j4flmao
backend-caching-strategies

Use this skill when the user says 'cache-aside', 'write-through', 'write-behind', 'read-through', 'cache invalidation', 'redis cache pattern', 'cache stampede', 'thundering herd', 'TTL jitter', 'stale cache'. Picks and implements a Redis-backed caching pattern (cache-aside, read-through, write-through, write-behind) with correct invalidation, stampede protection and failure handling. Do NOT use for: HTTP/CDN/browser caching (frontend-browser-caching), cache infrastructure sizing and eviction policy tuning (backend-caching), distributed locks as a primary goal (backend-distributed-locking).

نظرة عامة

الناشرj4flmao
المستودعagent-skills
اسم المهارةbackend-caching-strategies
النجوم
41
التفريعات
6
الملفات المرفقة
تعليمات فقط
الترخيصMIT
الروابط
  • تعليمات بصيغة Markdown

    ملف SKILL.md يُحمّله النموذج عند الحاجة، فلا يستهلك توكنات إلا عندما يَرِد طلب ذو صلة فعلًا.

  • تعمل مع أي نموذج لغوي كبير

    مهارات الذكاء الاصطناعي مكتوبة بصيغة Markdown وليست شيفرة خاصة بمزوّد معيّن، لذا تعمل مع GPT أو Claude أو Gemini أو Grok أو نموذج محلي.

  • مكتفية بذاتها

    كل ما يحتاجه النموذج موجود في التعليمات — لا ملفات إضافية لمزامنتها.

  • مفتوحة المصدر

    نشرها j4flmao على GitHub. اطّلع على المصدر قبل تثبيتها.

التثبيت

ثبّت مهارة الذكاء الاصطناعي Backend Caching Strategies في TypingMind لاستخدامها مع أي نموذج لغوي كبير، أو أضفها إلى وكيل ذكاء اصطناعي آخر يقرأ SKILL.md.

1

التثبيت في TypingMind

يُثبّت TypingMind المهارة مباشرةً من مجلدها على GitHub — فيقرأ SKILL.md، ويجمع ملفات الموارد في حزمة، ويحفظ النتيجة محليًا.

  1. افتح التطبيق وانتقل إلى «الإضافات» ثم «المهارات».
  2. اختر «تثبيت من GitHub».
  3. الصق رابط مجلد المهارة الموضّح أدناه وأكّد التثبيت.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/caching-strategies
  4. فعّل المهارة في كل محادثة تريد إتاحتها فيها.
الإضافات ← المهارات ← إضافة مهارة ← من رابط GitHub، ثم الصق رابط المجلد واضغط على «متابعة».
2

التثبيت في وكيل ذكاء اصطناعي آخر

يمكن لأي وكيل ذكاء اصطناعي يقرأ تنسيق Agent Skills استخدام هذه المهارة — انسخ المجلد إلى مجلد المهارات الخاص بذلك الوكيل.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/caching-strategies .claude/skills/backend-caching-strategies
أعد تشغيل Claude Code بعد النسخ ليتعرّف على المهارة الجديدة.

استخدمها في TypingMind

فعّل Backend Caching Strategies في أي محادثة على TypingMind وسيتولى النموذج الباقي. تتضمن مطالبة النظام اسمها ووصفها، وبمجرد ورود طلب ذي صلة، يُحمّل النموذج التعليمات الكاملة تلقائيًا — فلا تحتاج إلى استدعائها يدويًا، ولا تستهلك أي توكنات حتى تُستخدم فعليًا.

يُحمّل النموذج مهارة Backend Caching Strategies تلقائيًا بمجرد ورود طلب ذي صلة بها.

تعمل مع أي نموذج ذكاء اصطناعي

مهارات الذكاء الاصطناعي هي تعليمات بصيغة Markdown وليست شيفرة خاصة بمزوّد معيّن، لذا لا ترتبط Backend Caching Strategies بالنموذج الذي كُتبت له. ثبّتها مرة واحدة في TypingMind واستخدمها مع GPT-5 أو Claude أو Gemini أو Grok أو DeepSeek أو Mistral أو Llama أو نموذج محلي تشغّله بنفسك — كل ذلك باستخدام مفاتيح API الخاصة بك.

  • تُحمَّل عند الحاجة فقط

    تتضمن مطالبة النظام الاسم والوصف فقط. وتُجلب التعليمات عند أول طلب ذي صلة، لذا لا تستهلك تعليمات المهارة أي توكنات ما دامت المهارة غير مستخدمة.

  • بدّل النماذج أثناء المحادثة

    لأن المهارة تعليمات وليست شيفرة، فإن تغيير النموذج لا يعطّلها — فالنموذج التالي يقرأ ملف SKILL.md نفسه.

تعليمات المهارة

هذا هو محتوى SKILL.md الذي يُحمّله النموذج. اقرأه قبل التثبيت — فالمهارة عبارة عن تعليمات سيتبعها نموذجك.

Caching Strategies with Redis

Purpose

Choose the right application-level caching pattern for a data access path and implement it so that the cache never becomes a source of wrong answers or outages. Covers read/write patterns, invalidation, stampede protection, and behaviour when Redis is unavailable.

Agent Protocol

Trigger

Exact user phrases: "cache-aside", "write-through", "write-behind", "read-through", "cache invalidation", "redis cache pattern", "cache stampede", "thundering herd", "TTL jitter", "stale cache".

Input Context

  • Read/write ratio and acceptable staleness for the data.
  • Source of truth (PostgreSQL, MySQL, remote API) and who writes to it.
  • Language/client library (go-redis v9, ioredis/node-redis, redis-py, Lettuce).
  • Single Redis, Sentinel, or Cluster.

Output Artifact

Pattern choice with rationale plus code for read path, write path and invalidation. No files unless requested.

Response Format

Data: {entity / query}
Pattern: {cache-aside | read-through | write-through | write-behind}
Key: {key template}   TTL: {base} + jitter {range}
Invalidation: {delete-on-write | versioned key | event-driven}
Stampede guard: {singleflight | lock | early refresh | none}
Redis down: {fall through to DB | serve stale | fail}

Pattern Selection

PatternRead pathWrite pathConsistencyUse when
Cache-asideApp reads cache, on miss loads DB and populatesApp writes DB, then deletes keyEventual; short stale windowDefault for most read-heavy data
Read-throughCache layer/library loads on missSame as cache-asideSame as cache-asideYou want loading logic centralised in a cache wrapper
Write-throughCache always populatedApp writes DB and cache in the same requestStronger, but two writes can diverge on partial failureData read immediately after write, small hot set
Write-behindCache is primaryWrite to cache, flush to DB asynchronouslyRisk of data loss if cache dies before flushCounters, metrics, write-coalescing where loss is tolerable
Refresh-aheadBackground refresh before expiryn/aFresh for hot keysPredictable hot keys with expensive loads

Decision rules:

  • Default to cache-aside with delete-on-write. Delete instead of update: updating the cache after a DB write races with concurrent readers repopulating an older value.
  • Use write-behind only when you can tolerate losing the unflushed window, or when Redis persistence (AOF) plus an idempotent flusher is in place.
  • Never cache data whose staleness causes money or security errors (balances, permissions) without explicit invalidation on every write path.

Cache-Aside in Go (go-redis v9)

go
package cache

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"math/rand/v2"
	"time"

	"github.com/redis/go-redis/v9"
	"golang.org/x/sync/singleflight"
)

type User struct {
	ID    string `json:"id"`
	Email string `json:"email"`
}

type UserStore interface {
	GetUser(ctx context.Context, id string) (User, error)
	UpdateUser(ctx context.Context, u User) error
}

type UserCache struct {
	rdb   *redis.Client
	db    UserStore
	group singleflight.Group
	ttl   time.Duration
}

func NewUserCache(rdb *redis.Client, db UserStore) *UserCache {
	return &UserCache{rdb: rdb, db: db, ttl: 10 * time.Minute}
}

func userKey(id string) string { return "user:v1:" + id }

// jitter spreads expirations so keys written together do not expire together.
func (c *UserCache) jitteredTTL() time.Duration {
	return c.ttl + time.Duration(rand.Int64N(int64(c.ttl/10)))
}

func (c *UserCache) Get(ctx context.Context, id string) (User, error) {
	raw, err := c.rdb.Get(ctx, userKey(id)).Bytes()
	switch {
	case err == nil:
		var u User
		if jsonErr := json.Unmarshal(raw, &u); jsonErr == nil {
			return u, nil
		}
		slog.Warn("corrupt cache entry, reloading", "key", userKey(id))
	case errors.Is(err, redis.Nil):
		// miss: fall through to loader
	default:
		// Redis unavailable: degrade to the database instead of failing the request.
		slog.Warn("redis get failed, falling back to db", "key", userKey(id), "err", err)
	}

	// singleflight collapses concurrent misses for the same key into one DB query.
	v, err, _ := c.group.Do(id, func() (any, error) {
		u, err := c.db.GetUser(ctx, id)
		if err != nil {
			return User{}, fmt.Errorf("load user %s: %w", id, err)
		}
		if b, err := json.Marshal(u); err == nil {
			if err := c.rdb.Set(ctx, userKey(id), b, c.jitteredTTL()).Err(); err != nil {
				slog.Warn("redis set failed", "key", userKey(id), "err", err)
			}
		}
		return u, nil
	})
	if err != nil {
		return User{}, err
	}
	return v.(User), nil
}

// Update writes the source of truth first, then invalidates.
func (c *UserCache) Update(ctx context.Context, u User) error {
	if err := c.db.UpdateUser(ctx, u); err != nil {
		return fmt.Errorf("update user %s: %w", u.ID, err)
	}
	if err := c.rdb.Del(ctx, userKey(u.ID)).Err(); err != nil {
		// The entry will self-heal at TTL; log so stale windows are visible.
		slog.Error("cache invalidation failed", "key", userKey(u.ID), "err", err)
	}
	return nil
}

Notes:

  • singleflight only deduplicates within one process. Across many instances, combine it with a short Redis lock (SET key val NX PX 5000) or probabilistic early refresh.
  • Include a schema version in the key (user:v1:) so a deploy that changes the serialized shape does not read old entries.

Invalidation Strategies

StrategyHowTrade-off
TTL onlyEntry expiresSimple; staleness up to TTL
Delete on writeDEL after DB commitSmall race: a reader that loaded before the commit can repopulate old data
Delayed double deleteDEL, then DEL again after ~1sNarrows the race; extra write
Versioned keysStore a version counter, embed in keyNo deletes needed; old keys expire by TTL
Event-driven (CDC/outbox)Consumer deletes keys on change eventsCatches writes from every service; needs a pipeline

When several services write the same table, delete-on-write in one service is not enough. Use CDC (e.g. Debezium) or the transactional outbox to drive invalidation.

Stampede Protection

  1. Request coalescing (singleflight) per instance.
  2. Mutex on miss: SET lock:{key} {token} NX PX 5000; winners load, losers wait briefly and re-read, release with a compare-and-delete Lua script.
  3. Probabilistic early expiration: refresh when now - delta * beta * ln(rand()) >= expiry (XFetch), so one request refreshes before expiry.
  4. TTL jitter: always add 0-10% random jitter to TTLs set in bulk.
  5. Negative caching: cache "not found" for a short TTL to stop repeated misses for absent IDs.

Write-Behind Sketch

python
# Accumulate increments in Redis, flush periodically. Loss window = flush interval.
import redis

r = redis.Redis()

def record_view(article_id: int) -> None:
    r.hincrby("views:pending", str(article_id), 1)

def flush(conn) -> None:
    # Atomically take the pending hash so increments during flush are not lost.
    # Resume a batch left by a crashed flush before taking a new one.
    if not r.exists("views:flushing"):
        if not r.exists("views:pending"):
            return
        r.rename("views:pending", "views:flushing")
    pending = r.hgetall("views:flushing")
    with conn.cursor() as cur:
        for article_id, count in pending.items():
            cur.execute(
                "UPDATE articles SET views = views + %s WHERE id = %s",
                (int(count), int(article_id)),
            )
    conn.commit()
    r.delete("views:flushing")

If the flusher crashes between commit and delete, the next run re-applies the batch and double-counts; store a flush batch ID in the DB if exactness matters.

Anti-Patterns

Anti-patternProblemFix
Set cache before DB commitCache holds data that may roll backCommit first, then delete
Update cache on write instead of deleteConcurrent writers leave older value lastDelete and let the next read load
No TTLStale forever after a missed invalidationEvery key gets a TTL
Caching whole unbounded listsHuge values, slow serializationCache pages or IDs plus per-item entries
KEYS pattern for invalidationBlocks Redis (O(N) over keyspace)Track keys in a set, or use SCAN, or versioned keys
Treat Redis errors as misses that also fail the requestCache outage becomes full outageFall back to DB with a circuit breaker on Redis

Checklist

  • Pattern chosen with explicit staleness budget.
  • Every key has a TTL with jitter and a versioned prefix.
  • Writes commit to the source of truth before invalidating.
  • All write paths (including other services, admin tools, migrations) invalidate.
  • Stampede guard for hot or expensive keys.
  • Redis failure degrades to the database; hit/miss/error rates are metered.

References

  • Related skills: skills/backend/universal/caching/SKILL.md (cache infrastructure, eviction, multi-tier), skills/backend/universal/distributed-locking/SKILL.md (lock semantics), skills/backend/universal/transactional-outbox/SKILL.md (event-driven invalidation).

الأسئلة الشائعة

ماذا تفعل مهارة الذكاء الاصطناعي Backend Caching Strategies؟

Use this skill when the user says 'cache-aside', 'write-through', 'write-behind', 'read-through', 'cache invalidation', 'redis cache pattern', 'cache stampede', 'thundering herd', 'TTL jitter', 'stale cache'. Picks and implements a Redis-backed caching pattern (cache-aside, read-through, write-through, write-behind) with correct invalidation, stampede protection and failure handling. Do NOT use for: HTTP/CDN/browser caching (frontend-browser-caching), cache infrastructure sizing and eviction policy tuning (backend-caching), distributed locks as a primary goal (backend-distributed-locking).

لماذا تستخدم Backend Caching Strategies على TypingMind؟

لأنك تثبّتها مرة واحدة وتستخدمها مع أي نموذج. مهارة Backend Caching Strategies عبارة عن نص Markdown وليست شيفرة خاصة بمزود بعينه، لذا تعمل المهارة نفسها مع GPT-5 أو Claude أو Gemini أو Grok أو نموذج محلي، ويمكنك تبديل النموذج أثناء المحادثة دون تعطّل المهارة. يعمل TypingMind بمفاتيح API الخاصة بك، فتدفع للمزودين مباشرةً بدلًا من اشتراك لكل مقعد، وتبقى مهاراتك ومحادثاتك في مساحة التخزين الخاصة بك.

كيف أثبّت Backend Caching Strategies في TypingMind؟

في TypingMind، افتح «الإضافات»، ثم «المهارات»، ثم اختر «التثبيت من GitHub» والصق https://github.com/j4flmao/agent-skills/tree/main/skills/backend/caching-strategies. يقرأ TypingMind ملف SKILL.md الخاص بالمهارة ويثبّتها كمهارة يمكنك تفعيلها لكل محادثة على حدة.

ما نماذج الذكاء الاصطناعي التي يمكنها استخدام Backend Caching Strategies؟

أي نموذج تربطه في TypingMind. مهارات الذكاء الاصطناعي عبارة عن تعليمات Markdown وليست شيفرة خاصة بمزود بعينه، لذا يمكن لكل من GPT وClaude وGemini وGrok والنماذج المحلية تحميل هذه المهارة عندما يتوافق الطلب معها.

كم نموذج ذكاء اصطناعي يمكنني استخدامه مع Backend Caching Strategies؟

أي عدد تريده. ما دام النموذج يدعم المهارات، يمكنك استخدام Backend Caching Strategies معه، سواء كان GPT أو Claude أو Gemini أو Grok أو DeepSeek أو Mistral أو Llama أو غيرها، وكل ذلك على TypingMind باستخدام مفاتيح API الخاصة بك.

هل مهارة الذكاء الاصطناعي Backend Caching Strategies مجانية؟

نعم. نشرها j4flmao على GitHub بموجب ترخيص MIT. لا تدفع إلا لمزود الذكاء الاصطناعي الخاص بك مقابل التوكنات التي تستخدمها.

ما هي مهارات الذكاء الاصطناعي؟

مهارة الذكاء الاصطناعي حزمة تعليمات قابلة لإعادة الاستخدام تعلّم نموذج الذكاء الاصطناعي كيفية تنفيذ مهمة محددة. وتتبع تنسيق Agent Skills المفتوح: ملف SKILL.md يتضمن اسمًا ووصفًا، إلى جانب أي نصوص برمجية أو قوالب أو ملفات مرجعية قد يحتاج إليها النموذج. لا يقرأ النموذج التعليمات إلا عندما يتوافق طلبك مع المهارة، لذا لا تترتب على المهارة المثبتة أي تكلفة حتى تُستخدم.

كيف تختلف مهارات الذكاء الاصطناعي عن الإضافات أو موصلات MCP؟

تمنح الإضافة أو موصل MCP النموذج أدوات جديدة يمكنه استدعاؤها، وهي شيفرة تُنفَّذ في مكان ما وتُرجع نتيجة. أما مهارة الذكاء الاصطناعي فتزوّد النموذج بالمعرفة ومنهجية العمل: كيفية التعامل مع مهمة، والخطوات التي ينبغي اتباعها، وما ينبغي أن تكون عليه المخرجات الجيدة. المهارات عبارة عن نصوص Markdown، لذا لا تحتاج إلى خادم أو مفتاح API أو بيئة تشغيل، وتعمل مع أي نموذج.

عرض الكل

أنشئ مساحة عملك للذكاء الاصطناعي الآن

اشترك في نشرتنا الإخبارية لتصلك أخبار الميزات الجديدة والهدايا القادمة 👇