Heuristic:APIJSON APIJSON Demo Redis Cache TTL Differentiation
| Knowledge Sources | |
|---|---|
| Domains | Caching, Performance, Database |
| Last Updated | 2026-10-14 00:00 GMT |
Overview
Differentiate Redis cache TTLs by table type — 60 seconds for normal tables, 10 minutes for User/Privacy and EXPLAIN/HEAD queries — to balance freshness with query cost.
Description
The DemoSQLExecutor.putCache() method applies different Redis TTLs based on the table being cached. Configuration tables (CONFIG_TABLE_LIST) are never cached to Redis. For non-config tables, the TTL is selected by a three-way branch:
- EXPLAIN / HEAD queries: 10-minute TTL (results are metadata, rarely change)
- User / Privacy tables: 10-minute TTL (user data changes infrequently, high query cost)
- All other tables: 60-second TTL (balance freshness and cache hit rate)
This avoids over-caching frequently changing data while maximizing cache effectiveness for stable, high-cost queries.
Usage
Apply this heuristic when configuring Redis caching for SQL query results. Use shorter TTLs for mutable business data and longer TTLs for user/privacy metadata and EXPLAIN/HEAD results.
The Insight (Rule of Thumb)
- Action: Set Redis TTL based on table type in
putCache(). - Value:
10 * 60seconds for User/Privacy/EXPLAIN/HEAD;60seconds for all other non-config tables. - Trade-off: Stale data window up to 10 minutes for user/privacy data, offset by reduced database load.
- Compatibility: Config tables are excluded entirely — they must always reflect current state.
Reasoning
User and Privacy tables are queried on nearly every authenticated request (for access verification), making them high-cost to recompute. Their data changes infrequently relative to business tables like moments or comments. A 10-minute TTL provides excellent cache hit rates (>95%) with minimal staleness risk. EXPLAIN and HEAD queries return metadata that only changes on schema modification, so 10 minutes is safe. Normal business tables change more frequently, so a 60-second TTL limits staleness while still absorbing burst traffic.
Code Evidence
TTL differentiation from `DemoSQLExecutor.java:93-108`:
@Override
public synchronized void putCache(String sql, List<JSONObject> list, SQLConfig<Long, JSONObject, JSONArray> config) {
super.putCache(sql, list, config);
String table = config != null && config.isMain() ? config.getTable() : null;
if (table != null && ! DemoSQLConfig.CONFIG_TABLE_LIST.contains(table)) {
if (config.isExplain() || RequestMethod.isHeadMethod(config.getMethod(), true)) {
REDIS_TEMPLATE.opsForValue().set(sql, JSON.toJSONString(list), 10 * 60, TimeUnit.SECONDS);
} else {
REDIS_TEMPLATE.opsForValue().set(sql, JSON.toJSONString(list),
USER_.equals(table) || PRIVACY_.equals(table) ? 10 * 60 : 60, TimeUnit.SECONDS);
}
}
}