Principle:APIJSON APIJSON Demo SQL Caching
| Knowledge Sources | |
|---|---|
| Domains | Caching, Performance, Database |
| Last Updated | 2026-10-14 00:00 GMT |
Overview
Performance optimization that caches SQL query results in an external key-value store (Redis) to avoid redundant database queries, with TTL-based expiration and differentiated cache durations per table type.
Description
SQL Caching sits between SQL execution and the database. When a query is executed, the framework first checks the cache using the SQL string as the key. On a cache hit, results are returned directly without hitting the database. On a miss, the query executes against the database and the result is stored in the cache with a TTL.
This solves:
- Repeated query load: Common queries (e.g., user profiles) are executed many times with identical SQL, wasting database resources.
- Read latency: Cache hits return in milliseconds versus potentially hundreds of milliseconds for database queries.
- Cache invalidation: TTL-based expiration ensures stale data is eventually refreshed. DELETE operations use a delayed expiration (60s) to prevent cache stampede (thundering herd).
The implementation distinguishes between:
- Normal tables: 60-second TTL
- User/Privacy tables: 10-minute TTL (infrequently changed)
- Explain/HEAD queries: 10-minute TTL (metadata, rarely changes)
- Config tables: Not cached (always fresh)
Usage
Use this principle when:
- Building read-heavy APIs where the same queries are repeated frequently.
- You need to reduce database load without changing application logic.
- Different tables have different staleness tolerances (user profiles vs. real-time data).
Theoretical Basis
getCache(sql, config):
1. Check in-memory cache (super.getCache)
2. If miss: check Redis (REDIS_TEMPLATE.opsForValue().get(sql))
3. Return cached List<JSONObject> or null
putCache(sql, list, config):
1. Store in in-memory cache (super.putCache)
2. If table is NOT a config table:
- TTL = 60s for normal tables
- TTL = 10min for User/Privacy tables
- TTL = 10min for EXPLAIN/HEAD queries
3. Serialize as JSON string, store in Redis
removeCache(sql, config):
- For DELETE: REDIS_TEMPLATE.expire(sql, 60s) // delayed to prevent stampede
- For other methods: REDIS_TEMPLATE.delete(sql) // immediate invalidation
The cache-aside pattern means the application is responsible for checking and populating the cache — the database does not write to the cache automatically.
Related Pages
Implemented By
- Implementation:APIJSON_APIJSON_Demo_DemoSQLExecutor
- Implementation:APIJSON_APIJSON_Demo_DemoSQLExecutor_BigData
- Implementation:APIJSON_APIJSON_Demo_DemoSQLExecutor_SimpleDemo