Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Pair every cache read with a cache write in cache-aside code
When you add a cache lookup with an early return, also store the freshly computed value back to the cache; a get without a set means every request is a miss.
Bad example
| 1 | async function getReport(): Promise<Report> { |
| 2 | const cached = await cache.get<Report>('report'); |
| 3 | if (cached) return cached; |
| 4 |
|
| 5 | const report = await buildReport(); |
| 6 | return report; // never written back -> cache is always empty, every call recomputes |
| 7 | } |
Explanation (EN)
The early-return reads from the cache but nothing ever writes to it, so the cache stays empty and the expensive computation runs on every request.
Objašnjenje (HR)
Rani povratak cita iz cachea, ali nista u njega nikad ne pise, pa cache ostaje prazan i skupi izracun se izvrsava pri svakom zahtjevu.
Good example
| 1 | async function getReport(): Promise<Report> { |
| 2 | const cached = await cache.get<Report>('report'); |
| 3 | if (cached) return cached; |
| 4 |
|
| 5 | const report = await buildReport(); |
| 6 | await cache.set('report', report, CACHE_TTL_MS); |
| 7 | return report; |
| 8 | } |
Explanation (EN)
Writing the computed value back with a TTL completes the cache-aside pattern so subsequent calls hit the cache.
Objašnjenje (HR)
Upisivanje izracunate vrijednosti natrag s TTL-om upotpunjuje cache-aside obrazac pa sljedeci pozivi pogadaju cache.