Frappe Core Cache logo

Frappe Core Cache

Organization
Impertio-Studio
frappe-core-cache

Use when implementing Redis caching, cache invalidation, or distributed locking in Frappe. Prevents stale cache bugs, race conditions from missing locks, and memory bloat from unbounded cache keys. Covers frappe.cache(), @redis_cache decorator, cache.get_value/set_value, cache invalidation patterns, frappe.lock, TTL strategies. Keywords: cache, Redis, redis_cache, invalidation, locking, frappe.cache, get_value, set_value, TTL, distributed lock, data not refreshing, stale data, cache not clearing, Redis error, slow repeated queries..

Overview

PublisherImpertio-Studio
RepositoryFrappe_Claude_Skill_Package
Skill namefrappe-core-cache
Stars
180
Forks
53
Bundled files
3
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 3 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by Impertio-Studio on GitHub. Read the source before you install it.

Installation

Install the Frappe Core Cache AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package.git /tmp/Frappe_Claude_Skill_Package
mkdir -p .claude/skills
cp -r /tmp/Frappe_Claude_Skill_Package/skills/source/core/frappe-core-cache .claude/skills/frappe-core-cache
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Frappe Core Cache in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Frappe Core Cache on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Frappe Core Cache is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Frappe Cache & Locking

Quick Reference

ActionMethodNotes
Set valuefrappe.cache.set_value(key, val)With optional TTL
Get valuefrappe.cache.get_value(key)Returns None if missing
Get or generatefrappe.cache.get_value(key, generator=fn)Calls fn() on cache miss
Delete valuefrappe.cache.delete_value(key)Single key or list of keys
Delete by patternfrappe.cache.delete_keys(pattern)Wildcard * matching
Hash setfrappe.cache.hset(name, key, val)Redis hash field
Hash getfrappe.cache.hget(name, key)Single hash field
Hash get allfrappe.cache.hgetall(name)Full hash as dict
Hash deletefrappe.cache.hdel(name, key)Remove hash field
Hash existsfrappe.cache.hexists(name, key)Returns bool
Cached documentfrappe.get_cached_doc(dt, dn)Full doc from cache
Clear doc cachefrappe.clear_document_cache(dt, dn)Invalidate cached doc
Decorator cache@redis_cacheAuto-cache function result
Request cachefrappe.local.cachePer-request dict (not Redis)

Decision Tree

What caching pattern do you need?
├─ Cache a function result automatically?
│  ├─ Pure function (same args → same result) → @redis_cache
│  └─ Need custom key/TTL → manual get_value/set_value
├─ Cache a document?
│  ├─ Read-only access → frappe.get_cached_doc()
│  └─ Need to invalidate → frappe.clear_document_cache()
├─ Cache structured data (multiple fields)?
│  └─ Redis hash → hset/hget/hgetall
├─ Per-request cache (avoid repeated DB calls in one request)?
│  └─ frappe.local.cache dict
├─ Prevent concurrent execution?
│  └─ Distributed lock → frappe.lock("resource_name")
└─ Invalidate cache?
   ├─ Single key → delete_value(key)
   ├─ Pattern → delete_keys("prefix*")
   └─ All site cache → frappe.clear_cache()

String Operations

Set and Get

python
# Set a value (persists until evicted or deleted)
frappe.cache.set_value("exchange_rate_USD", 1.08)

# Set with TTL (expires after N seconds)
frappe.cache.set_value("exchange_rate_USD", 1.08, expires_in_sec=3600)

# Get value (returns None if missing)
rate = frappe.cache.get_value("exchange_rate_USD")

# Get with generator (calls function on cache miss, stores result)
rate = frappe.cache.get_value(
    "exchange_rate_USD",
    generator=lambda: fetch_exchange_rate("USD"),
)

User-Scoped Values

python
# Store per-user preference
frappe.cache.set_value("dashboard_layout", "compact", user="user@example.com")

# Retrieve for specific user
layout = frappe.cache.get_value("dashboard_layout", user="user@example.com")

Delete

python
# Single key
frappe.cache.delete_value("exchange_rate_USD")

# Multiple keys
frappe.cache.delete_value(["exchange_rate_USD", "exchange_rate_EUR"])

# Pattern-based deletion (wildcard)
frappe.cache.delete_keys("exchange_rate*")

Hash Operations

Use hashes to group related fields under a single key.

python
# Set hash fields
frappe.cache.hset("config|notifications", "email_enabled", True)
frappe.cache.hset("config|notifications", "sms_enabled", False)
frappe.cache.hset("config|notifications", "max_retries", 3)

# Get single field
email_on = frappe.cache.hget("config|notifications", "email_enabled")

# Get all fields as dict
config = frappe.cache.hgetall("config|notifications")
# {"email_enabled": True, "sms_enabled": False, "max_retries": 3}

# Delete field
frappe.cache.hdel("config|notifications", "sms_enabled")

# Check existence
exists = frappe.cache.hexists("config|notifications", "email_enabled")

Hash with Generator

python
# hget with generator — calls function on miss
value = frappe.cache.hget(
    "user|permissions",
    "user@example.com",
    generator=lambda: compute_permissions("user@example.com"),
)

@redis_cache Decorator

Automatically cache function return values based on arguments.

python
from frappe.utils.caching import redis_cache

@redis_cache
def get_item_price(item_code, price_list):
    """Expensive query — cached automatically."""
    return frappe.db.get_value("Item Price",
        {"item_code": item_code, "price_list": price_list},
        "price_list_rate",
    )

# First call — hits database, stores in Redis
price = get_item_price("ITEM-001", "Standard Selling")

# Second call — returns from cache
price = get_item_price("ITEM-001", "Standard Selling")

# Clear all cached results for this function
get_item_price.clear_cache()

With TTL

python
@redis_cache(ttl=300)  # expires after 5 minutes
def get_exchange_rate(from_currency, to_currency):
    return fetch_rate_from_api(from_currency, to_currency)

Rules for @redis_cache:

  • ALWAYS ensure arguments are hashable (strings, numbers, tuples). NEVER pass dicts or lists as arguments.
  • ALWAYS call .clear_cache() when underlying data changes.
  • NEVER use on functions with side effects — the function will NOT execute on cache hits.

frappe.local.cache: Request-Scoped Cache

frappe.local.cache is a plain Python dict that lives for the duration of a single HTTP request. It is NOT stored in Redis.

python
def get_user_settings():
    """Avoid repeated DB calls within a single request."""
    if "user_settings" not in frappe.local.cache:
        frappe.local.cache["user_settings"] = frappe.get_doc(
            "User Settings", frappe.session.user
        )
    return frappe.local.cache["user_settings"]

Use frappe.local.cache when:

  • The same data is needed multiple times in one request
  • The data does NOT need to persist across requests
  • You want zero Redis overhead

Document Caching

python
# Get cached document (read-only, no permission check)
settings = frappe.get_cached_doc("System Settings")
item = frappe.get_cached_doc("Item", "ITEM-001")

# Invalidate when document changes
frappe.clear_document_cache("Item", "ITEM-001")

# Cached single value
val = frappe.db.get_value("Item", "ITEM-001", "item_name", cache=True)

NEVER modify a document returned by frappe.get_cached_doc() — it returns a shared reference. Modifications corrupt the cache for all subsequent reads.


Distributed Locking

Prevent concurrent execution of critical sections using Redis-based locks.

python
# Context manager (recommended)
with frappe.lock("process_payroll"):
    # Only one worker executes this block at a time
    process_all_salary_slips()
    # Lock auto-released on exit

# Manual lock/unlock
frappe.lock("inventory_sync")
try:
    sync_inventory()
finally:
    frappe.unlock("inventory_sync")  # ALWAYS unlock in finally

Rules:

  • ALWAYS use with frappe.lock() (context manager) to guarantee release.
  • NEVER hold locks for more than a few seconds — long locks cause worker starvation.
  • ALWAYS use descriptive lock names to avoid collisions.

Cache Invalidation Patterns

Pattern 1: TTL-Based (Time-to-Live)

python
frappe.cache.set_value("dashboard_stats", compute_stats(), expires_in_sec=300)

Best for: Data that can be slightly stale (exchange rates, dashboard aggregates).

Pattern 2: Event-Based Invalidation

python
# In hooks.py
doc_events = {
    "Item Price": {
        "on_update": "my_app.cache.invalidate_price_cache",
        "on_trash": "my_app.cache.invalidate_price_cache",
    }
}

# In my_app/cache.py
def invalidate_price_cache(doc, method):
    frappe.cache.delete_keys("item_price*")
    # Or clear specific function cache:
    # get_item_price.clear_cache()

Best for: Data that MUST be fresh immediately after changes.

Pattern 3: Hybrid (TTL + Event)

python
@redis_cache(ttl=600)
def get_pricing_rules():
    return frappe.get_all("Pricing Rule", fields=["*"])

# Event hook clears cache immediately on change
def on_pricing_rule_update(doc, method):
    get_pricing_rules.clear_cache()

Best for: Frequently read data with occasional updates.


Common Cache Keys (Internal)

Key PatternContent
doctype::meta::{dt}DocType metadata
user_permissions::{user}User permission cache
bootinfo::{user}User boot info
notifications::{user}Notification counts
document_cache::{dt}::{dn}Cached document

NEVER write to internal cache keys directly. ALWAYS use the documented API methods (get_cached_doc, clear_document_cache, etc.).


Performance Guidelines

  1. ALWAYS set TTL on cached values that derive from external data — without TTL, stale data persists until manual invalidation or Redis eviction.
  2. NEVER cache large objects (>1 MB) — Redis uses pickle serialization, and large values increase serialization overhead and memory usage.
  3. ALWAYS use frappe.local.cache for data needed multiple times within a single request — it avoids Redis round-trips entirely.
  4. NEVER use frappe.clear_cache() as a routine invalidation strategy — it clears ALL cache keys for the site, causing a cold-cache performance hit.
  5. ALWAYS prefix custom cache keys with your app name (e.g., myapp|exchange_rate) to avoid collisions with Frappe internals.

Redis Configuration

Default config: {bench}/config/redis_cache.conf

SettingDefaultDescription
Port13000Redis cache port
Bind127.0.0.1Listen address
maxmemory-policyallkeys-lruEviction policy
maxmemory256mbMax memory (adjustable)

Key Namespacing

All cache keys are automatically prefixed by Frappe with the site name:

python
# You write:
frappe.cache.set_value("my_key", "value")

# Redis stores:
# "mysite.localhost|my_key"

frappe.cache.make_key(key, user, shared) handles prefixing. The shared=True parameter removes the site prefix for cross-site keys (rare use case).


Version Differences

Featurev14v15v16
frappe.cache.set_valueAvailableAvailableAvailable
@redis_cacheNot availableAvailableAvailable
@redis_cache(ttl=)Not availableAvailableAvailable
frappe.lock context mgrAvailableAvailableAvailable
frappe.local.cacheAvailableAvailableAvailable
hget with generatorAvailableAvailableAvailable

See Also

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Frappe Core Cache AI skill do?

Use when implementing Redis caching, cache invalidation, or distributed locking in Frappe. Prevents stale cache bugs, race conditions from missing locks, and memory bloat from unbounded cache keys. Covers frappe.cache(), @redis_cache decorator, cache.get_value/set_value, cache invalidation patterns, frappe.lock, TTL strategies. Keywords: cache, Redis, redis_cache, invalidation, locking, frappe.cache, get_value, set_value, TTL, distributed lock, data not refreshing, stale data, cache not clearing, Redis error, slow repeated queries..

Why use Frappe Core Cache on TypingMind?

Because you install it once and use it with any model. Frappe Core Cache is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Frappe Core Cache in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package/tree/main/skills/source/core/frappe-core-cache. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Frappe Core Cache?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Frappe Core Cache?

As many as you like. As long as a model supports skills, you can use Frappe Core Cache with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Frappe Core Cache AI skill free?

Yes. It is published on GitHub by Impertio-Studio under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇