Skip to main content

Caching Strategy

Related docs: Hosting Infrastructure · SDLC/DESIGN · Microservices


1. Redis Deployment

Redis runs as a system service on the same EC2 instance as the core services, accessible only within the VPC (port 6379 blocked at security group level for external traffic).

Connection string:

REDIS_URL=redis://localhost:6379

Recommended production configuration (/etc/redis/redis.conf):

maxmemory 2gb
maxmemory-policy allkeys-lru
save "" # Disable RDB persistence (ephemeral by design)
appendonly no # Disable AOF (data reconstructable from DB)
requirepass your_password # Enable auth in production

1.1 Redis Database Allocation

DBPurposeServices
0Production sessions, carts, rate limiting, general cacheAll production services
1Test environment (CI, local dev)Test suites
2BullMQ job queuesscheduler, backend, notifications
3Tracking pub/sub channelstracking service
4Recommendations cacherecommendations service
5Feature flags cacheconfig service
6Analytics cacheanalytics service
7Fraud detection cachefraud service

2. Use Cases and Key Conventions

2.1 User Sessions

Sessions are stored in Redis using a JWT reference map (not the full JWT payload).

Key patternsession:{sessionId}
Value{ userId, role, expiresAt } (JSON)
TTL7 days (rolling; refreshed on each authenticated request)
InvalidationDEL session:{sessionId} on logout; KEYS session:* scan on global logout

2.2 Cart Data

Cart contents are persisted in Redis for guest and authenticated users alike.

Key patterncart:{userId} or cart:guest:{fingerprint}
Value{ items: [...], updatedAt } (JSON)
TTL30 days
InvalidationOn order placement (clearCart()) or manual cart clear

Migration: On login, any guest cart (cart:guest:*) is merged into the authenticated cart and the guest key deleted.

2.3 Rate Limiting

Express API uses a Redis-backed sliding-window rate limiter.

Key patternratelimit:{ip}:{endpoint}
ValueRequest count (integer)
TTL15 minutes
Limit1,000 requests / 15 min (general); 20 requests / 15 min (payment initiation); 20 requests / 15 min (auth)

Payment endpoints have a stricter limit to prevent brute-force USSD spam.

2.4 Temporary Payment Status Cache

After a webhook updates an order's payment status, the result is cached briefly to reduce DB polling pressure.

Key patternpayment_status:{orderId}
Value{ paymentStatus, updatedAt } (JSON)
TTL60 seconds
InvalidationAuto-expiry; webhook handler sets the key after each update

The GET /api/v1/payments/status/:orderId endpoint reads from this cache first, falling back to the database.

2.5 Product Listing Cache

Frequently accessed product listing pages are cached to reduce DB load.

Key patternproducts:{queryHash}
ValueSerialised product list + pagination (JSON)
TTL5 minutes
InvalidationDEL products:* on product create/update/delete (via a cache invalidation hook in the product service)

2.6 Search Cache

Meilisearch results are cached for popular queries.

Key patternsearch:{queryHash}
ValueSerialised search results (JSON)
TTL2 minutes
InvalidationAuto-expiry; product index updates trigger selective invalidation

2.7 Feature Flags Cache

Feature flags from the config service are cached in Redis for fast access.

Key patternfeature_flags:{flagKey}
ValueBoolean or JSON configuration
TTL1 hour
InvalidationAdmin toggles flag → config service invalidates all feature_flags:* keys

2.8 Fraud Detection Cache

Temporary fraud scoring data is cached to enable velocity checks.

Key patternfraud:velocity:{ip}:{hourBucket}
Value{ paymentCount, amountTotal, lastPaymentAt } (JSON)
TTL1 hour
InvalidationAuto-expiry
Key patternfraud:risk_score:{userId}
Value{ score, calculatedAt, factors: [...] } (JSON)
TTL24 hours
InvalidationNew payment triggers recalculation

2.9 Tracking Location Cache

Latest agent location is cached for fast retrieval.

Key patterntracking:location:{orderId}
Value{ lat, lng, accuracy, timestamp, speed, heading } (JSON)
TTL5 minutes
InvalidationAuto-expiry; new location update overwrites

2.10 Analytics Cache

Pre-aggregated analytics data for dashboards.

Key patternanalytics:{metric}:{granularity}:{date}
ValueAggregated metric data (JSON)
TTL1 hour (hourly), 24 hours (daily), 7 days (weekly)
InvalidationAuto-expiry; new data triggers background recalculation

3. Key Naming Summary

PrefixUse caseTTLDB
session:{id}User session7 days0
cart:{userId}Authenticated cart30 days0
cart:guest:{fp}Guest cart30 days0
ratelimit:{ip}:{ep}Rate limiting15 min0
payment_status:{orderId}Payment status cache60 sec0
products:{hash}Product listing cache5 min0
search:{hash}Search results cache2 min0
feature_flags:{key}Feature flags1 hour5
fraud:velocity:{ip}Fraud velocity tracking1 hour7
fraud:risk_score:{userId}Fraud risk score24 hours7
tracking:location:{orderId}Agent location5 min3
analytics:{metric}Analytics aggregates1h-7d6
bullmq:{queue}Job queue metadataVaries2
recommendations:{userId}Product recommendations1 hour4

4. Cache Invalidation Rules

EventCache keys invalidated
User logoutsession:{sessionId}
Order placedcart:{userId}, payment_status:{orderId}
Product created / updated / deletedproducts:*, search:*, recommendations:*
Webhook updates payment statuspayment_status:{orderId} (overwritten, not deleted)
Admin clears all sessionssession:* (scan + delete)
Feature flag toggledfeature_flags:*
Fraud rule updatedfraud:risk_score:*
New tracking locationtracking:location:{orderId} (overwritten)
Settlement completedanalytics:settlements:*

5. Pub/Sub Channels

5.1 Tracking Channels

ChannelPublisherSubscribersPurpose
order:{orderId}:locationtracking serviceWebSocket clientsLive location updates
order:{orderId}:statusbackendWebSocket clientsOrder status changes
order:{orderId}:arrivingtracking servicenotification serviceGeofence trigger

5.2 Notification Channels

ChannelPublisherSubscribersPurpose
user:{userId}:notificationsnotifications serviceSSE clientsReal-time in-app notifications
broadcast:alladmin dashboardAll SSE clientsPlatform-wide announcements

6. Observability

All Redis operations are traced via Middleware.io OpenTelemetry instrumentation. Cache hit/miss ratios are visible in the Middleware.io dashboard under the redis span group.

Alert thresholds:

MetricThresholdAction
Cache memory > 80%AlertRisk of eviction; review TTLs or scale Redis
Redis connection errors > 5/minCriticalInvestigate network or Redis health
Cache hit rate < 70%WarningReview cache key design or TTL values
Pub/Sub message lag > 5sWarningCheck subscriber health

For internal use only. Do not distribute outside Pakashop engineering.