Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/analytics-engine/patterns.md
1# Analytics Engine Patterns23## Use Cases45| Use Case | Key Metrics | Index On |6|----------|-------------|----------|7| API Metering | requests, bytes, compute_units | api_key |8| Feature Usage | feature, action, duration | user_id |9| Error Tracking | error_type, endpoint, count | customer_id |10| Performance | latency_ms, cache_status | endpoint |11| A/B Testing | variant, conversions | user_id |1213## API Metering (Billing)1415```typescript16env.ANALYTICS.writeDataPoint({17blobs: [pathname, method, status, tier],18doubles: [1, computeUnits, bytes, latencyMs],19indexes: [apiKey]20});2122// Query: Monthly usage by customer23// SELECT index1 AS api_key, SUM(double2) AS compute_units24// FROM usage WHERE timestamp >= DATE_TRUNC('month', NOW()) GROUP BY index125```2627## Error Tracking2829```typescript30env.ANALYTICS.writeDataPoint({31blobs: [endpoint, method, errorName, errorMessage.slice(0, 1000)],32doubles: [1, timeToErrorMs],33indexes: [customerId]34});35```3637## Performance Monitoring3839```typescript40env.ANALYTICS.writeDataPoint({41blobs: [pathname, method, cacheStatus, status],42doubles: [latencyMs, 1],43indexes: [userId]44});4546// Query: P95 latency by endpoint47// SELECT blob1, quantile(0.95)(double1) AS p95_ms FROM perf GROUP BY blob148```4950## Anti-Patterns5152| ❌ Wrong | ✅ Correct |53|----------|-----------|54| `await writeDataPoint()` | `writeDataPoint()` (fire-and-forget) |55| `indexes: [method]` (low cardinality) | `blobs: [method]`, `indexes: [userId]` |56| `blobs: [JSON.stringify(obj)]` | Store ID in blob, full object in D1/KV |57| Write every request at 10M/min | Pre-aggregate per second |58| Query from Worker | Query from external service/API |5960## Best Practices61621. **Design schema upfront** - Document blob/double/index assignments632. **Always include count metric** - `doubles: [latency, 1]` for AVG calculations643. **Use enums for blobs** - Consistent values like `Status.SUCCESS`654. **Handle sampling** - Use ratios (avg_latency = SUM(latency)/SUM(count))665. **Test queries early** - Validate schema before heavy writes6768## Schema Template6970```typescript71/**72* Dataset: my_metrics73*74* Blobs:75* blob1: endpoint, blob2: method, blob3: status76*77* Doubles:78* double1: latency_ms, double2: count (always 1)79*80* Indexes:81* index1: customer_id (high cardinality)82*/83```84