# Redis Strategy for POS-Backend

This document explains where Redis will be effective in your backend, where it should not be used, and how to roll it out safely.

## Quick Recommendation

Use Redis for:
- analytics response caching
- short-lived report job state
- rate limiting counters
- optional JWT/session blacklists (if you need forced logout)

Do not use Redis for:
- source of truth business data (products, bills, invoices, loans)
- strong consistency stock updates
- backup payload storage

For your current workflow, the highest impact is analytics caching.

## Where Redis is Most Effective

### 1) Analytics endpoints (highest ROI)

Target endpoints:
- GET /api/v1/analytics/kpi
- GET /api/v1/analytics/net-profit
- GET /api/v1/analytics/daily-sales
- GET /api/v1/analytics/product-performance
- GET /api/v1/analytics/category-distribution
- GET /api/v1/analytics/recent-transactions
- GET /api/v1/analytics/stock
- GET /api/v1/analytics/expenses
- GET /api/v1/analytics/expired-batches/:batchId

Why:
- these endpoints run heavy aggregation pipelines
- many users load same dashboard repeatedly
- read-heavy and tolerates small staleness

Suggested TTL:
- dashboard cards/charts: 120 to 300 seconds
- stock/expired batches: 60 to 180 seconds
- recent transactions: 30 to 120 seconds

Cache key pattern:
- analytics:{endpoint}:{timeRange}:{from}:{to}:{role}:{branch}
- example: analytics:stock:7d:::admin:main

Invalidation triggers:
- on bill create/update/delete
- on invoice create/update/delete
- on product stock or expiry update
- on product-batch receive/update/delete
- on expense create/update/delete

Practical approach:
- start with TTL-only caching first
- add targeted invalidation as second step

### 2) Report generation workflows

Use Redis for:
- job status: queued, running, done, failed
- progress tracking for long exports/PDF
- temporary download token metadata

Do not store large PDF or backup file content in Redis.
Store files on disk and keep only metadata in Redis.

Suggested TTL:
- job state: 10 to 60 minutes
- temporary download token: 5 to 30 minutes

### 3) Rate limiting

Use Redis-backed rate limiting for:
- auth/login routes
- backup import/export routes
- heavy analytics/report routes

Why:
- robust counters across processes
- protects CPU/DB from bursts

### 4) Optional auth controls

If required by business rules, use Redis for:
- token denylist on logout/password reset
- short-lived OTP/reset code storage

If you keep simple stateless JWT only, this is optional.

## Where Redis Should NOT Be Used

### 1) Core transaction data

Do not make Redis primary storage for:
- bills, invoices, loan payments, expenses, orders
- products and stock quantities
- product-batch quantities

Reason:
- MongoDB is your source of truth
- transactional correctness matters more than speed

### 2) Stock mutation path

Do not cache-write stock changes through Redis first.
- Stock and batch deductions must go directly to MongoDB.
- You can cache read models, not write authority.

### 3) Backup payloads

Do not put full backup JSON in Redis.
- backup files can be large
- Redis memory is expensive
- disk-based backup strategy is already correct for this project

### 4) Rarely-used admin endpoints

If endpoint traffic is low and query is cheap, skip Redis to reduce complexity.

## Recommended Rollout Plan (In Order)

### Phase 1 (immediate)
- Add Redis client and health check.
- Cache analytics responses with TTL only.
- Add cache miss/hit logging for analytics routes.

Success metric:
- analytics p95 latency drops by 60 percent or more.

### Phase 2
- Add event-driven invalidation keys for analytics groups:
  - analytics:stock:*
  - analytics:kpi:*
  - analytics:expenses:*
- Keep fallback to DB when Redis is down.

Success metric:
- stale analytics complaints stay low while cache hit rate improves.

### Phase 3
- Add Redis store for rate limiter.
- Add report job status caching.

Success metric:
- fewer timeout spikes during peak dashboard usage.

## Engineering Rules for Safe Use

- Always fail open: if Redis fails, continue with MongoDB query.
- Never return 500 only because cache is unavailable.
- Set explicit TTL on every key.
- Namespace keys by module.
- Avoid caching user-sensitive payloads unless key-scoped by user/role.
- Log cache hit/miss and DB fallback.

## Suggested Key Namespaces

- analytics:*  (dashboard and charts)
- reports:jobs:*  (job states)
- ratelimit:*  (throttle counters)
- auth:denylist:*  (optional forced logout)

## Minimal Invalidations You Need

On write operations in these modules, clear related namespaces:
- bills -> analytics:kpi:*, analytics:daily-sales:*, analytics:product-performance:*, analytics:recent-transactions:*
- invoices -> same as bills plus net-profit where used
- products -> analytics:stock:*, analytics:category-distribution:*
- product-batches -> analytics:stock:*, analytics:expired-batches:*
- expenses -> analytics:expenses:* and net-profit if included

## Final Decision Matrix

Use Redis now:
- analytics caching
- rate limiting
- report job status

Use Redis later (optional):
- auth denylist and OTP

Do not use Redis:
- stock write path
- transaction source data
- full backups

This gives you speed where needed without risking accounting and inventory correctness.
