# ADR 0011: Calculate analytics sections lazily and cache them in Redis - Status: Accepted - Date: 2026-08-20 ## Context The hackathon dataset is static after its one-time bootstrap. Continuously refreshing analytics would spend resources before a merchant requests them. A first calculation may contain several independent dashboard sections, and the user should see completed sections without waiting for the slowest query. Production ZarinPal write integration is outside the MVP. ## Decision On first dashboard access, an authenticated idempotent `POST` creates or returns the current analytics run for that merchant/dataset-snapshot/metric-definition version. It enqueues four section ids—`overview`, `payment_performance`, `fees`, and `peer_comparison`—for bounded parallel calculation by a separate Go worker service. This worker is event-driven, not scheduled. Use `github.com/hibiken/asynq` pinned to `v0.26.0` as the Redis-backed queue/worker library. Asynq is explicitly pre-`v1.0.0`, and its public API may change without a major-version increment. Do not float the dependency or upgrade it without reviewing release notes, API compatibility, Redis compatibility, retry/deduplication behavior, and integration tests. Cache each completed typed section in Redis using a key derived from the sole completed import-run snapshot, merchant id, period, metric-definition version, and section id. Use a 30-day TTL. Redis-backed idempotency/single-flight coordination prevents duplicate equivalent jobs. A future explicitly replaced dataset would require a newly specified namespace-selection rule. Expose a separate authenticated `GET` SSE endpoint for the run. Stream stable event ids and typed events for section started, section ready, section failed, overall complete, and heartbeat. Support safe reconnect without exposing another merchant’s jobs or values. One section failure does not suppress sections that succeeded. Give each section attempt a 60-second timeout. Retry only classified transient failures at most twice, for a maximum of three attempts. Use exponential backoff with jitter (initial nominal delay 1 second, then 2 seconds; jitter prevents synchronized retry bursts). Do not retry authorization, validation, unsupported-metric, or other deterministic failures. Default worker concurrency to 16 jobs globally and 4 per merchant. Enforce the global value in the worker and the merchant value in queue middleware/coordination; both are validated environment settings. Apply authenticated rate limits independently from job deduplication: - analytics start: 10 requests/minute in independent per-user and per-merchant buckets, burst 3; - manual retry: 3 requests/10 minutes in independent per-user and per-merchant buckets, burst 1; - SSE: 2 concurrent connections per user and 4 per merchant. Return `429 Too Many Requests` with `Retry-After` before enqueuing work. A manual retry targets only one exhausted failed section for the current dataset snapshot and is idempotent; it cannot restart ready siblings. Send SSE heartbeat events every 15 seconds. Retain run events for one hour for authorized `Last-Event-ID` replay. After replay retention expires, return/provide the current run snapshot and continue from new events rather than replaying another merchant’s or an unbounded event history. Payment facts are immutable during the MVP, so PostgreSQL contains no cache-revision tables or invalidation triggers. Explicit dataset replacement is an administrative recovery workflow: it selects a different completed import run as the active snapshot and therefore creates a different Redis namespace. Any future live-write integration must define insert/update/delete invalidation in a separately approved specification. Redis is a private disposable cache and coordination system, not a source of truth. PostgreSQL remains authoritative. Cached values contain approved aggregates only and exclude raw rows, payer-card keys, credentials, session tokens, and cross-tenant details. ## Consequences - All dashboard analytics begin together, while the UI reveals each section independently as it completes. - Redis loss or key expiry causes safe lazy recomputation; Redis is excluded from backup/restore requirements. - No scheduled refresh or time-based freshness claim is required. - The deployment includes private Redis and on-demand analytics-worker services. - Rate limits and concurrency values remain environment-configurable but changes require security/load evidence and a reviewed spec/config change. - The pre-1.0 Asynq pin creates upgrade risk; CI uses the committed Go module/checksum files and upgrades are deliberate. - Snapshot selection, tenant isolation, job deduplication, partial failures, SSE reconnect, and cache data minimization require integration/security tests. ## References - Asynq repository and stability notice: - Pinned release: