# Helpdesk Module — Performance Review

## Overview

Performance analysis of the Helpdesk module covering query patterns, indexing, caching opportunities, and scalability concerns.

---

## 1. Database Indexing

### 1.1 Current Indexes

| Model | Index | Columns |
|-------|-------|---------|
| Queue | `tenant_is_active_sort_order` | (tenant, is_active, sort_order) |
| Category | `tenant_queue_is_active` | (tenant, queue, is_active) |
| Tag | `helpdesk_tag_unique_per_tenant` | (tenant, name) — unique constraint |
| SLAPolicy | `tenant_is_active` | (tenant, is_active) |
| Ticket | `tenant_status_created` | (tenant, status, -created_at) |
| Ticket | `tenant_queue_status` | (tenant, queue, status) |
| Ticket | `tenant_assigned_to_status` | (tenant, assigned_to, status) |
| Ticket | `tenant_priority_status` | (tenant, priority, status) |
| Ticket | `tenant_first_response_due` | (tenant, first_response_due_at) |
| Ticket | `tenant_resolution_due` | (tenant, resolution_due_at) |
| TicketReply | `ticket_is_internal_created` | (ticket, is_internal, created_at) |
| SLATimer | `due_at_paused_resolved` | (due_at, is_paused, is_resolved) |
| Automation | `tenant_is_active_sort` | (tenant, is_active, sort_order) |
| AgentTeam | `tenant_is_active_sort` | (tenant, is_active, sort_order) |

### 1.2 Index Adequacy
- **Ticket listing**: Covered by composite indexes on `(tenant, status, -created_at)`, `(tenant, queue, status)`, `(tenant, assigned_to, status)`.
- **SLA checks**: `due_at` index on SLATimer supports efficient breach scanning.
- **Soft-delete**: `is_deleted` is indexed on all soft-deletable models via `db_index=True`.
- **Full-text search**: Delegated to platform global search engine; no DB text indexes needed.

---

## 2. Query Patterns

### 2.1 N+1 Risks
- **TicketDetailPage**: Uses `select_related("queue", "category", "sla_policy")` in views.
- **Ticket replies**: `prefetch_related("replies")` not always used; reply listing could trigger N+1 if not prefetched.
- **Agent teams**: `prefetch_related("memberships__user")` recommended for team detail views.

### 2.2 Expensive Queries
- **Reports summary**: Aggregates across tickets grouped by queue; consider materialized view or caching for high-volume tenants.
- **Automation evaluation**: ProcessEngine runs synchronously on each matching event; for high-volume tenants, consider async (Celery) dispatch.
- **SLA breach scanning**: Celery periodic task scans `due_at < now` timers; interval should be tuned (currently ~5 minutes recommended).

---

## 3. Caching Strategy

### 3.1 Implemented
- No explicit caching in the helpdesk module.

### 3.2 Recommended
| Data | Strategy | TTL | Rationale |
|------|----------|-----|-----------|
| Queue list | Per-tenant cache | 5 min | Rarely changes, listed frequently |
| Category tree | Per-tenant cache | 5 min | Hierarchical, rarely changes |
| SLA policies | Per-tenant cache | 10 min | Configuration, very stable |
| User list (agents) | Per-tenant cache | 2 min | Changes infrequently |
| Settings | Per-tenant cache | 1 min | Configuration, checked on every request |
| Reports summary | Per-tenant cache | 5 min | Computationally expensive |

---

## 4. API Performance

### 4.1 Pagination
- Uses DRF's `PageNumberPagination` (offset-based).
- Default page size: 25 items.
- Recommended: evaluate cursor-based pagination for high-throughput ticket listing.

### 4.2 Serialization
- Ticket serializers are selective: list views return lightweight representations, detail views include full nested data.
- No over-fetching of related models in list endpoints.

### 4.3 Rate Limiting
- Not enforced at module level. Recommended for:
  - Ticket creation: 60/min per tenant
  - Reply addition: 120/min per agent
  - Report generation: 10/min per tenant

---

## 5. Asynchronous Processing

### 5.1 Celery Tasks
- `check_sla_breaches`: Periodic task scanning overdue SLA timers.
- `auto_close_tickets`: Periodic task closing resolved tickets past auto-close threshold.
- `send_csat_surveys`: Periodic task sending CSAT surveys after resolution.

### 5.2 Event Processing
- Event subscribers run synchronously in-band (SLA timers, automations, notifications).
- For high volume (>100 tickets/min), consider dispatching automations and notifications to Celery.

---

## 6. Scalability Notes

### 6.1 Horizontal Scaling
- Stateless API servers: No session affinity required.
- Database: All queries are indexed; no cross-tenant joins.
- Event bus: In-process event bus will need replacement with Redis/RabbitMQ for multi-instance deployments.

### 6.2 Multi-Tenant Considerations
- No cross-tenant queries by design.
- Tenant-level settings allow per-tenant quotas (`max_tickets`).
- Database-level tenant isolation ready for future sharding (tenant FK on every table).

---

## 7. AI Performance

### 7.1 Suggestion Generation
- `AITicketSuggestion` creation is a simple DB insert.
- Actual AI model calls happen in the platform AI app layer, not in helpdesk.
- Suggestion approval is transactional (atomic apply + audit log).

### 7.2 Audit Log Growth
- `AIActionLog` rows are append-only.
- For high-volume AI usage, consider partitioning by `tenant_id` or archiving logs older than 90 days.
- Index on `(tenant_id, created_at)` supports efficient time-range queries.

---

## Review History

| Date | Reviewer | Notes |
|------|----------|-------|
| 2026-06-11 | Automated review (Phase 9) | Initial performance review. Index coverage is good. Caching and async processing recommendations documented. |

