128 lines
3.9 KiB
Markdown
128 lines
3.9 KiB
Markdown
# Subtask: Analytics Recording and Storage
|
|
|
|
**Parent Task**: Decomp/001
|
|
**Subtask ID**: Decomp/001-06
|
|
**Dependencies**: Decomp/001-01 (Database Schema)
|
|
|
|
## Description
|
|
Implement analytics recording system for tracking URL clicks. Must handle high-volume writes (100K req/sec) without blocking redirect requests.
|
|
|
|
## Requirements
|
|
- Record click data: timestamp, user-agent, IP, referrer
|
|
- Batch inserts for performance (not row-by-row)
|
|
- Non-blocking operation (async queue)
|
|
- Handle geo-location lookup (optional)
|
|
- Survive database failures gracefully
|
|
- Support analytics queries
|
|
|
|
## Technical Specifications
|
|
|
|
### Data Collection Architecture
|
|
|
|
```python
|
|
# Async queue for buffering analytics events
|
|
class AnalyticsBuffer:
|
|
def __init__(self, max_size=10000, flush_interval=5):
|
|
self.buffer = []
|
|
self.max_size = max_size
|
|
self.flush_interval = flush_interval # seconds
|
|
self.lock = asyncio.Lock()
|
|
|
|
async def add(self, event: dict):
|
|
"""Add event to buffer, flush if full."""
|
|
async with self.lock:
|
|
self.buffer.append(event)
|
|
if len(self.buffer) >= self.max_size:
|
|
await self._flush()
|
|
|
|
async def _flush(self):
|
|
"""Batch insert all buffered events."""
|
|
if not self.buffer:
|
|
return
|
|
|
|
try:
|
|
await db.execute_many(
|
|
"""INSERT INTO url_analytics (url_id, clicked_at, user_agent, ip_address, referrer)
|
|
VALUES ($1, $2, $3, $4, $5)""",
|
|
self.buffer
|
|
)
|
|
self.buffer.clear()
|
|
except Exception as e:
|
|
# Log error but don't crash
|
|
logger.error(f"Analytics flush failed: {e}")
|
|
# Keep buffer to retry later
|
|
```
|
|
|
|
### Geo-location Lookup (Optional Enhancement)
|
|
|
|
```python
|
|
async def enrich_geo_location(event: dict) -> dict:
|
|
"""Add geo-location data to analytics event."""
|
|
try:
|
|
ip = event.get('ip_address')
|
|
if not ip or ip in ('127.0.0.1', '::1'):
|
|
return event
|
|
|
|
# Use MaxMind GeoLite2 or similar
|
|
geo_data = await geoip_lookup(ip)
|
|
event['country_code'] = geo_data.get('country_code')
|
|
event['city'] = geo_data.get('city')
|
|
except Exception:
|
|
pass # Geo-location failure not critical
|
|
|
|
return event
|
|
```
|
|
|
|
### Background Worker
|
|
|
|
```python
|
|
async def analytics_worker():
|
|
"""Background task to periodically flush analytics buffer."""
|
|
buffer = AnalyticsBuffer()
|
|
|
|
while True:
|
|
try:
|
|
await asyncio.sleep(buffer.flush_interval)
|
|
await buffer.flush()
|
|
except Exception as e:
|
|
logger.error(f"Analytics worker error: {e}")
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
- [ ] Analytics events captured for all redirects
|
|
- [ ] Batch inserts (not single-row)
|
|
- [ ] Non-blocking operation (redirect latency unaffected)
|
|
- [ ] Survives database failures (drop events, don't crash)
|
|
- [ ] Flush interval: 5 seconds or 10K events
|
|
- [ ] Unit tests for buffer overflow and error handling
|
|
|
|
## Notes
|
|
- **Why async queue**: Decouples redirect latency from analytics write speed
|
|
- **Batch size**: 10K events balances memory usage and DB efficiency
|
|
- **Flush interval**: 5 seconds limits data loss on failure
|
|
- **Trade-off**: Accept data loss on crash vs. synchronous writes (chosen async)
|
|
|
|
## Alternative: Message Queue (Scale-up Path)
|
|
For 1M+ events/sec, replace in-memory buffer with:
|
|
- Redis Streams
|
|
- Kafka
|
|
- RabbitMQ
|
|
|
|
## Edge Cases
|
|
- Buffer overflow → flush immediately, drop if still full
|
|
- Database connection lost → keep buffering, alert, drop when full
|
|
- Malformed user-agent → store as-is, don't validate
|
|
- IPv6 addresses → store in INET column (PostgreSQL handles this)
|
|
- Private IP ranges → skip geo-location lookup
|
|
|
|
## Performance Targets
|
|
- Memory usage: <100MB for 10K event buffer
|
|
- Flush time: <1 second for 10K batch insert
|
|
- Zero impact on redirect latency
|
|
|
|
## Monitoring
|
|
- Buffer size alerts
|
|
- Flush success/failure rate
|
|
- Events per second throughput
|
|
- Database insert latency
|