RUM Pipeline with Sampling and Privacy Gates
As Sherlock, I'll deduce and construct a complete, production-ready Real User Monitoring (RUM) pipeline blueprint. This handles high-volume telemetry from browsers (e.g., Core Web Vitals, errors, interactions) with sampling (to control costs/volume) and privacy gates (client/server-side PII scrubbing, consent checks, GDPR/CCPA compliance).
Key Design Principles
- Scalability: Handles 1M+ events/sec via edge ingestion + streaming.
- Sampling:
- Client-side: Probabilistic (e.g., 10% of sessions).
- Server-side: Tail/reservoir sampling for errors.
- Privacy Gates:
- Gate 1 (Client): Consent check, IP truncation, PII hashing.
- Gate 2 (Server): Full PII regex strip, user ID pseudonymization.
- Tech Stack (Open-source, self-hostable):
| Component | Tool |
|---|
| Client SDK | Custom JS (Web Vitals + Beacon API) |
| Edge/Ingest | Cloudflare Workers (or Nginx) |
| Queue | Apache Kafka |
| Processing | Apache Flink (or Kafka Streams) |
| Storage | ClickHouse (OLAP for queries) |
| Viz | Grafana |
- Cost: ~$0.01/GB ingested (after 90% sampling).
- Compliance: Consent flag mandatory; data retention 90 days.
Architecture Diagram (Mermaid-style text)
Client (Browser)
↓ [Privacy Gate 1: Consent + 10% Sampling + Hash PII]
Beacon/POST (gzip JSON)
↓
Edge Gateway (Cloudflare Worker)
↓ [Rate Limit: 1000 reqs/min/user]
Server Ingester (Go/Node)
↓ [Privacy Gate 2: PII Strip + Tail Sampling 1%]
Kafka Topics (rum-raw, rum-sampled)
↓
Flink Processor (Enrich + Aggregate)
↓ [Metrics: LCP/P95, Error Rates]
ClickHouse (Partitioned by date/device)
↓
Grafana Dashboards (Alerts on P95 > 2.5s)
1. Client-Side SDK (JavaScript)
Embed this <script> in your web app's <head>. Collects Web Vitals, errors, clicks. Privacy Gate 1 baked in.
<script>
(function() {
// Privacy Gate 1: Consent Check (use your CMP like OneTrust)
if (!localStorage.getItem('rumConsent')) return; // Block if no consent
// Config: Probabilistic sampling (10% of sessions)
const SAMPLE_RATE = 0.1;
if (Math.random() > SAMPLE_RATE) return;
// Anonymize early
const anonIP = `${location.hostname.split('.')[0]}.anon`; // Truncate IP-like
const sessionId = btoa(Math.random().toString()).slice(0, 16); // Pseudo-random
const userId = btoa(navigator.userAgent).slice(0, 32); // Hash UA
// Collect metrics (Web Vitals)
const metrics = {};
webVitals.getCLS(m => metrics.cls = m.value);
webVitals.getFID(m => metrics.fid = m.value);
webVitals.getLCP(m => metrics.lcp = m.value);
webVitals.getFCP(m => metrics.fcp = m.value);
// Errors & Interactions
window.addEventListener('error', e => metrics.error = { msg: e.message, stack: e.error?.stack?.slice(0, 1000) });
document.addEventListener('click', e => metrics.interactions = (metrics.interactions || 0) + 1);
// Send on load/unload (Beacon API = fire-and-forget)
window.addEventListener('load', () => {
const payload = {
timestamp: Date.now(),
url: location.href.split('?')[0], // Strip query params
device: { ua: navigator.userAgent.slice(0, 200), screen: `${screen.width}x${screen.height}` },
sessionId, userId, anonIP,
metrics,
consent: true // Flag for auditing
};
navigator.sendBeacon('/rum/ingest', new Blob([JSON.stringify(payload)], { type: 'application/json' }));
});
})();
</script>
<script src="https://unpkg.com/web-vitals"></script>
2. Edge Gateway (Cloudflare Worker)
Deploy this Worker on yourdomain.workers.dev/rum/*. Handles rate-limiting.
// wrangler.toml: [rules] pattern = "/rum/*"
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname !== '/rum/ingest') return new Response('404', { status: 404 });
// Rate limit: 1000/min per IP (Cloudflare KV)
const ip = request.headers.get('CF-Connecting-IP');
const key = `rum:${ip}`;
const count = await RUM_KV.get(key, { type: 'json' }) || 0;
if (count > 1000) return new Response('Rate Limited', { status: 429 });
await RUM_KV.put(key, count + 1, { expirationTtl: 60 });
// Proxy to backend (gzip preserved)
return fetch('https://your-backend.com/rum/ingest', request);
},
};
3. Server Ingester (Go - High Perf)
Run as go run ingester.go. Privacy Gate 2 + Sampling.
package main
import (
"bufio"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"regexp"
"strings"
"time"
"github.com/Shopify/sarama" // Kafka producer
)
type RumEvent struct {
Timestamp int64 `json:"timestamp"`
URL string `json:"url"`
UserID string `json:"userId"` // Will hash
// ... other fields
}
var piiRegex = regexp.MustCompile(`(?i)(email|phone|ssn|passport)[:=]?[a-z0-9@._-]{3,}`) // Strip PII
func privacyGate2(event *RumEvent) {
// Hash userId
h := sha256.Sum256([]byte(event.UserID))
event.UserID = hex.EncodeToString(h[:])[:16]
// Strip PII from all strings
// (Apply recursively to metrics.error.msg, etc.)
event.URL = piiRegex.ReplaceAllString(event.URL, "[REDACTED]")
}
func handler(w http.ResponseWriter, r *http.Request) {
var event RumEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
http.Error(w, "Bad JSON", 400); return
}
// Tail Sampling: 1% for errors, 0.1% otherwise
if strings.Contains(event.URL, "error") {
if rand.Float64() > 0.01 { return } // Drop 99%
} else if rand.Float64() > 0.001 { return }
privacyGate2(&event)
// Produce to Kafka
producer, _ := sarama.NewSyncProducer([]string{"kafka:9092"}, nil)
defer producer.Close()
producer.SendMessage(&sarama.ProducerMessage{
Topic: "rum-sampled",
Value: sarama.StringEncoder(fmt.Sprintf("%v", event)),
})
w.WriteHeader(204) // Ack
}
func main() {
rand.Seed(time.Now().UnixNano())
http.HandleFunc("/rum/ingest", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
4. Streaming Processor (Apache Flink - SQL)
Use Flink SQL for enrichment/aggregation. Deploy on Kubernetes.
-- Flink Table from Kafka
CREATE TABLE rum_raw (
timestamp BIGINT,
url STRING,
userId STRING,
lcp DOUBLE,
WATERMARK FOR timestamp AS timestamp - INTERVAL '5' SECOND
) WITH (
'connector' = 'kafka',
'topic' = 'rum-sampled',
'properties.bootstrap.servers' = 'kafka:9092'
);
-- Aggregate to ClickHouse sink
CREATE TABLE rum_agg WITH (
'connector' = 'jdbc', -- ClickHouse JDBC
'url' = 'jdbc:clickhouse://ch:8123/default'
) LIKE rum_raw (INCLUDING ALL);
INSERT INTO rum_agg
SELECT
tumble_start(timestamp, INTERVAL '1' MINUTE) as window_start,
url,
approx_count_distinct(userId) as unique_users,
percentile_cont(0.95)(lcp) as p95_lcp,
count(*) as events
FROM rum_raw
GROUP BY tumble(timestamp, INTERVAL '1' MINUTE), url;
5. Storage & Visualization
- ClickHouse Setup:
CREATE TABLE rum_agg (
window_start DateTime,
url LowCardinality(String),
unique_users UInt64,
p95_lcp Float64,
events UInt64
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(window_start)
ORDER BY (window_start, url);
- Grafana: Add ClickHouse DSN. Dashboard query:
SELECT p95_lcp, events FROM rum_agg
WHERE window_start > now() - INTERVAL 1 DAY
ORDER BY p95_lcp DESC LIMIT 10;
- Panels: Heatmap (LCP), Alerts (P95 > 2.5s).
Deployment & Ops
- Infra: Docker Compose for Kafka/Flink/ClickHouse (use Bitnami helm charts on K8s).
- Retention: ClickHouse TTL
DELETE TTL window_start + INTERVAL 90 DAY.
- Monitoring: Prometheus scrapes Flink, Grafana for meta-metrics.
- Testing:
curl -X POST -d '{"lcp":2.5}' http://localhost:8080/rum/ingest.
- Scale: Auto-scale ingester pods; Kafka partitions = 16.
This pipeline drops 99% volume via sampling while preserving signal (e.g., errors oversampled). Audit logs in Kafka rum-audit for consent/PII. Questions? The game is afoot! 🕵️