We are going to design a RUM (Real User Monitoring) pipeline with the following components:
- Sampling: To reduce the volume of data, we will implement a sampling strategy at the client (browser) or server (edge) level.
- Privacy Gates: To ensure privacy, we will have mechanisms to filter or anonymize sensitive data (PII, etc.) before it leaves the user's device or at the edge.
- Dashboards: To visualize the collected data, we will set up a dashboard that can query and display the RUM data.
Steps:
-
Data Collection (Client-side):
- We will use a JavaScript snippet (like the RUM agent) that runs in the user's browser.
- The agent will collect performance metrics (like page load time, resource timings, etc.) and user interactions (clicks, etc.).
- The agent will also have the ability to sample events (e.g., only send 1 out of every 100 page views) to reduce data volume.
-
Privacy Gates:
- We must ensure that no PII is collected. We can do this by:
a. Not collecting certain data (e.g., avoid collecting form field values).
b. Anonymizing IP addresses (if we collect them) or not collecting them at all.
c. Using a privacy filter that runs on the client or at the edge to remove any sensitive information that might have been collected by mistake.
- We can also implement a consent management system (CMP) to only collect data if the user has consented.
-
Data Transmission:
- The collected and filtered data will be sent to an endpoint (our server or a third-party service) via HTTP (usually POST).
- We should use HTTPS to ensure data in transit is encrypted.
-
Data Ingestion and Storage:
- We need a server that can receive the RUM data and store it in a database or data warehouse.
- We might use a message queue (like Kafka) for handling high volume and then process and store the data.
-
Data Processing:
- We may need to process the data (e.g., aggregate, filter further) before storing or for dashboard queries.
-
Dashboards:
- We will set up a dashboard (using tools like Grafana, Kibana, or a custom solution) that can query the stored data and display metrics such as:
- Page load times (by page, by browser, by device, etc.)
- Error rates
- User journey funnels
- Geographical distribution (if we have location data and it's allowed by privacy laws)
Implementation:
Let's break down the code for each part:
-
Client-side RUM Agent (JavaScript):
We'll create a simple RUM agent that:
- Collects basic performance metrics using the Performance API.
- Samples events (e.g., 1% of page views).
- Filters out any sensitive data (by not collecting it in the first place).
- Sends the data to our endpoint.
Example:
(function() {
// Configuration
const SAMPLE_RATE = 0.01; // 1% sampling
// Check if we should sample this page view
if (Math.random() > SAMPLE_RATE) {
return;
}
// Collect performance data
const navigationEntry = performance.getEntriesByType('navigation')[0];
const resourceEntries = performance.getEntriesByType('resource');
// We can also collect custom user interactions (like clicks) but be cautious of PII.
// Build the payload
const payload = {
url: window.location.href,
// We might want to hash the URL to avoid PII in the path, but note that hashing might not be reversible and we might lose some context.
// Alternatively, we can remove query parameters or only keep the pathname.
// Let's keep only the pathname and hash it? Or just remove query string and fragment.
// We'll remove query string and fragment for privacy.
path: window.location.pathname,
// We can also collect the user agent, but be cautious because it can be used to identify a user in combination with other data.
// We might want to truncate or hash the user agent? Or just collect the browser and OS version without the full string.
// Let's collect only the browser name and version and OS, but we have to parse the user agent. Alternatively, we can use a library or just send the full user agent and then process it on the server.
// For simplicity, we'll send the full user agent and then process on the server. But note: user agent can contain PII? Usually not, but it's a fingerprinting vector.
userAgent: navigator.userAgent,
// We'll collect the timing data
timing: {
// We can collect the navigation timing
domContentLoaded: navigationEntry ? navigationEntry.domContentLoadedEventEnd - navigationEntry.startTime : null,
loadEvent: navigationEntry ? navigationEntry.loadEventEnd - navigationEntry.startTime : null,
// We can also collect other metrics like First Contentful Paint, etc. if available.
},
// We might also want to collect errors
errors: window.performance && window.performance.getEntriesByType('error') || [],
// We can also collect custom metrics (like business metrics) but be cautious.
};
// Send the data
navigator.sendBeacon('/rum/ingest', JSON.stringify(payload));
})();
However, note that the above is a very simple example. In production, we might use an existing RUM library (like OpenReplay, LogRocket, etc.) or build a more robust one.
-
Architecture Overview
[Browser] → [Sampling Layer] → [Privacy Gate] → [Ingestion] → [Storage] → [Dashboard]
│ │ │ │ │
└─ Consent ────┴── Anonymization ─┴── Validation ─┴── Aggregation
1. SAMPLING LAYER
Client-Side Sampling (JavaScript)
// rum-sampler.js
class RUMSampler {
constructor(config) {
this.sampleRate = config.sampleRate || 0.1; // 10% default
this.sessionSampleRate = config.sessionSampleRate || 1.0;
this.sessionId = this.getSessionId();
this.pageLoadId = this.generateUUID();
}
shouldSample() {
// Session-based sampling (ensure consistency within session)
if (Math.random() > this.sessionSampleRate) return false;
// Global random sampling
return Math.random() < this.sampleRate;
}
generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
getSessionId() {
let sessionId = localStorage.getItem('rum_session_id');
if (!sessionId) {
sessionId = this.generateUUID();
localStorage.setItem('rum_session_id', sessionId);
}
return sessionId;
}
// Dynamic sampling adjustment based on traffic
adaptiveSampling(trafficVolume) {
const baseRate = this.sampleRate;
if (trafficVolume > 10000) { // events/sec
return Math.max(0.001, baseRate * 0.5); // Reduce sampling by 50%
}
return baseRate;
}
}
Edge Sampling (Cloudflare Workers / Fastly Compute)
// edge-sampler.js
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
// Sample by URL pattern
const pathname = url.pathname;
const sampleRates = {
'/checkout': 0.5, // 50% for checkout
'/admin': 0.1, // 10% for admin
'/api/health': 0.0, // 0% for health checks
'default': 0.1 // 10% default
};
const sampleRate = sampleRates[pathname] || sampleRates.default;
if (Math.random() > sampleRate) {
return new Response('Sampled out', { status: 204 });
}
// Add sampling metadata
const modifiedRequest = new Request(request);
modifiedRequest.headers.set('X-RUM-Sampled', 'true');
modifiedRequest.headers.set('X-RUM-Sample-Rate', sampleRate.toString());
return fetch(modifiedRequest);
}
2. PRIVACY GATES
Client-Side Privacy Filter
// privacy-filter.js
class PrivacyFilter {
constructor() {
this.piiPatterns = [
// Email
/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
// Phone numbers (US/International)
/(\+\d{1,3}\s?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/g,
// SSN (partial)
/\b\d{3}-\d{2}-\d{4}\b/g,
// Credit card (Luhn algorithm check)
/\b(?:\d{4}[-\s]?){3}\d{4}\b/g,
// IP addresses (will be hashed anyway)
/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g
];
this.sensitiveFields = [
'password', 'token', 'secret', 'key', 'auth', 'creditcard',
'cvv', 'ssn', 'social', 'passport', 'dob'
];
}
sanitize payload() {
// 1. Remove sensitive query parameters
if (payload.url) {
payload.url = this.sanitizeURL(payload.url);
}
// 2. Filter custom attributes
if (payload.custom) {
payload.custom = this.filterSensitiveFields(payload.custom);
}
// 3. Hash user identifiers
if (payload.user && payload.user.id) {
payload.user.id = this.hash(payload.user.id);
}
// 4. Remove PII from text fields
this.scrubTextFields(payload);
return payload;
}
sanitizeURL(url) {
try {
const urlObj = new URL(url);
// Remove all query parameters except non-sensitive ones
const safeParams = ['utm_', 'ref', 'gclid', 'fbclid'];
const params = new URLSearchParams(urlObj.search);
for (const [key] of params) {
if (!safeParams.some(safe => key.startsWith(safe))) {
params.delete(key);
}
}
urlObj.search = params.toString();
return urlObj.toString();
} catch {
return url; // Return original if URL parsing fails
}
}
filterSensitiveFields(obj, path = '') {
if (typeof obj !== 'object' || obj === null) return obj;
const result = {};
for (const [key, value] of Object.entries(obj)) {
const fullPath = path ? `${path}.${key}` : key;
if (this.sensitiveFields.some(field =>
fullPath.toLowerCase().includes(field))) {
result[key] = '[REDACTED]';
} else if (typeof value === 'object') {
result[key] = this.filterSensitiveFields(value, fullPath);
} else {
result[key] = value;
}
}
return result;
}
scrubTextFields(obj) {
const textFields = ['message', 'error', 'description', 'name'];
for (const field of textFields) {
if (obj[field] && typeof obj[field] === 'string') {
obj[field] = this.redactPII(obj[field]);
}
}
}
redactPII(text) {
let redacted = text;
for (const pattern of this.piiPatterns) {
redacted = redacted.replace(pattern, '[REDACTED]');
}
return redacted;
}
hash(value) {
// Use SHA-256 with salt (implement in production)
return btoa(value).slice(0, 16); // Simple base64 truncation for demo
}
}
Server-Side Privacy Gateway (Express.js Middleware)
// privacy-gateway.js
const express = require('express');
const { pipeline } = require('stream');
const { Transform } = require('stream');
class PrivacyTransform extends Transform {
constructor(options) {
super({ ...options, objectMode: true });
this.sensitiveKeys = new Set([
'password', 'token', 'secret', 'authorization',
'cookie', 'set-cookie', 'x-api-key'
]);
}
_transform(chunk, encoding, callback) {
try {
const sanitized = this.deepSanitize(JSON.parse(chunk));
this.push(JSON.stringify(sanitized));
callback();
} catch (error) {
callback(error);
}
}
deepSanitize(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
if (Array.isArray(obj)) {
return obj.map(item => this.deepSanitize(item));
}
const result = {};
for (const [key, value] of Object.entries(obj)) {
const lowerKey = key.toLowerCase();
// Remove sensitive headers/fields
if (this.sensitiveKeys.has(lowerKey) ||
lowerKey.includes('password') ||
lowerKey.includes('key')) {
result[key] = '[REDACTED]';
continue;
}
// Hash IP addresses
if (lowerKey === 'ip' || lowerKey === 'remote_addr') {
result[key] = this.hashIP(value);
continue;
}
// Recursively sanitize nested objects
result[key] = this.deepSanitize(value);
}
return result;
}
hashIP(ip) {
// Truncate/obfuscate IP for privacy (last octet for IPv4)
if (ip.includes('.')) {
const parts = ip.split('.');
return `${parts[0]}.${parts[1]}.${parts[2]}.0`; // /24 mask
}
return ip; // IPv6 handling needed
}
}
// Middleware
function privacyGateway(req, res, next) {
if (req.body && req.body.rumData) {
const filter = new PrivacyTransform();
pipeline(
req.body.rumData,
filter,
(err) => {
if (err) {
console.error('Privacy filtering error:', err);
return res.status(400).json({ error: 'Invalid data' });
}
req.body.rumData = filter.sanitizedData;
next();
}
);
} else {
next();
}
}
3. INGESTION & STORAGE
Ingestion API (Node.js/Express)
// ingestion.js
const express = require('express');
const { Kafka } = require('kafkajs');
const { v4: uuidv4 } = require('uuid');
const app = express();
app.use(express.json({ limit: '1mb' }));
// Kafka setup for streaming
const kafka = new Kafka({
clientId: 'rum-ingester',
brokers: [process.env.KAFKA_BROKERS]
});
const producer = kafka.producer();
// Batch processing configuration
const BATCH_SIZE = 100;
const BATCH_TIMEOUT = 5000; // 5 seconds
let batch = [];
let batchTimer = null;
async function sendBatch() {
if (batch.length === 0) return;
try {
await producer.send({
topic: 'rum-events',
messages: batch.map(event => ({
key: event.sessionId,
value: JSON.stringify(event),
timestamp: event.timestamp
}))
});
console.log(`Sent ${batch.length} events to Kafka`);
} catch (error) {
console.error('Kafka send error:', error);
// Implement retry logic with dead-letter queue
} finally {
batch = [];
clearTimeout(batchTimer);
batchTimer = null;
}
}
// Batched ingestion endpoint
app.post('/api/v1/rum', async (req, res) => {
try {
const events = Array.isArray(req.body) ? req.body : [req.body];
// Validate schema
for (const event of events) {
if (!event.type || !event.timestamp) {
return res.status(400).json({
error: 'Missing required fields (type, timestamp)'
});
}
// Add metadata
event.id = uuidv4();
event.ingestedAt = new Date().toISOString();
event.version = '1.0';
}
// Add to batch
batch.push(...events);
// Send batch if size threshold reached
if (batch.length >= BATCH_SIZE) {
sendBatch();
} else if (!batchTimer) {
// Set timeout for batch
batchTimer = setTimeout(sendBatch, BATCH_TIMEOUT);
}
res.status(202).json({
accepted: events.length,
queued: batch.length
});
} catch (error) {
console.error('Ingestion error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Initialize producer
producer.connect();
Storage Schema (ClickHouse)
-- rum_events table (raw events)
CREATE TABLE rum_events (
id String,
session_id String,
page_load_id String,
user_id String, -- hashed/anonymized
event_type String,
timestamp DateTime64(3),
url String,
path String,
referrer String,
user_agent String,
browser_name String,
browser_version String,
os_name String,
device_type String,
country_code String, -- from IP geolocation
region String,
city String,
load_time Float64,
dom_content_loaded Float64,
first_paint Float64,
first_contentful_paint Float64,
largest_contentful_paint Float64,
cumulative_layout_shift Float64,
error_message String,
error_stack String,
custom_metrics String, -- JSON
metadata String -- JSON
) ENGINE = MergeTree()
PARTITION BY toYYYYMMDD(timestamp)
ORDER BY (timestamp, session_id, event_type)
TTL timestamp + INTERVAL 90 DAY;
-- Aggregated table for dashboards
CREATE TABLE rum_aggregated_daily (
date Date,
path String,
browser_name String,
country_code String,
pv_count UInt64,
visitor_count Distinct(session_id),
avg_load_time Float64,
p95_load_time Float64,
error_rate Float64,
bounce_rate Float64
) ENGINE = AggregatingMergeTree()
PARTITION BY date
ORDER BY (date, path, browser_name, country_code);
4. DASHBOARDS
Grafana Dashboard Definition (JSON)
{
"dashboard": {
"title": "RUM Performance Dashboard",
"panels": [
{
"id": 1,
"title": "Page Load Time (p95)",
"type": "timeseries",
"targets": [
{
"expr": "quantile(0.95)(load_time) by (path)",
"legendFormat": "{{path}}"
}
]
},
{
"id": 2,
"title": "Core Web Vitals",
"type": "stat",
"targets": [
{
"expr": "avg(first_contentful_paint)",
"legendFormat": "FCP"
},
{
"expr": "avg(largest_contentful_paint)",
"legendFormat": "LCP"
},
{
"expr": "avg(cumulative_layout_shift)",
"legendFormat": "CLS"
}
]
},
{
"id": 3,
"title": "Error Rate by Browser",
"type": "barchart",
"targets": [
{
"expr": "sum(error_rate) by (browser_name)",
"legendFormat": "{{browser_name}}"
}
]
},
{
"id": 4,
"title": "Geographic Distribution",
"type": "table",
"targets": [
{
"expr": "sum(pv_count) by (country_code) | sort desc",
"format": "table"
}
]
}
],
"templating": {
"list": [
{
"name": "path",
"query": "distinct(path) from rum_events",
"includeAll": true
},
{
"name": "date_range",
"type": "interval",
"current": {
"text": "Last 24 hours",
"value": "24h"
}
}
]
}
}
}
Custom Dashboard (React + Recharts)
// RUMDashboard.jsx
import React, { useState, useEffect } from 'react';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
import { Card, Select, DatePicker } from 'antd';
const RUMDashboard = () => {
const [data, setData] = useState([]);
const [selectedPath, setSelectedPath] = useState('all');
const [dateRange, setDateRange] = useState('24h');
useEffect(() => {
fetchRUMData();
}, [selectedPath, dateRange]);
const fetchRUMData = async () => {
const response = await fetch(
`/api/analytics?path=${selectedPath}&range=${dateRange}`
);
const result = await response.json();
setData(result);
};
const CoreWebVitalsCard = () => (
<Card title="Core Web Vitals" size="small">
<div className="metrics-grid">
<MetricItem
label="LCP"
value={data.lcp}
threshold={2.5}
unit="s"
/>
<MetricItem
label="FID"
value={data.fid}
threshold={100}
unit="ms"
/>
<MetricItem
label="CLS"
value={data.cls}
threshold={0.1}
unit=""
/>
</div>
</Card>
);
return (
<div className="rum-dashboard">
<header className="dashboard-header">
<h1>Real User Monitoring</h1>
<div className="controls">
<Select
value={selectedPath}
onChange={setSelectedPath}
options={[]} // Populate from API
/>
<DatePicker.RangePicker onChange={(dates) => setDateRange(dates)} />
</div>
</header>
<div className="dashboard-grid">
<CoreWebVitalsCard />
<Card title="Performance Over Time">
<LineChart data={data.timeline}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="time" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="loadTime" stroke="#8884d8" />
<Line type="monotone" dataKey="fcp" stroke="#82ca9d" />
</LineChart>
</Card>
<Card title="Error Distribution">
<BarChart data={data.errors}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="browser" />
<YAxis />
<Tooltip />
<Bar dataKey="count" fill="#ff7300" />
</BarChart>
</Card>
</div>
</div>
);
};
5. MONITORING & ALERTING
Alert Rules (Prometheus Alertmanager)
# rum-alerts.yml
groups:
- name: rum_alerts
rules:
- alert: HighErrorRate
expr: |
sum(rate(rum_events{event_type="error"}[5m]))
/
sum(rate(rum_events[5m])) > 0.05
for: 2m
labels:
severity: critical
annotations:
summary: "High error rate detected"
description: "Error rate is {{ $value }}% (threshold: 5%)"
- alert: SlowPageLoad
expr: |
quantile_over_time(0.95, rum_load_time[1h]) > 3
for: 10m
labels:
severity: warning
annotations:
summary: "Slow page loads detected"
description: "P95 load time is {{ $value }}s (threshold: 3s)"
- alert: DataDrop
expr: |
rate(rum_events_total[5m]) < 0.5 * avg_over_time(rum_events_total[1h])
for: 5m
labels:
severity: warning
annotations:
summary: "Significant data drop detected"
6. DEPLOYMENT CONFIGURATION
Docker Compose for Local Development
version: '3.8'
services:
zookeeper:
image: confluentinc/cp-zookeeper:7.0.1
environment:
ZOOKEEPER_CLIENT_PORT: 2181
kafka:
image: confluentinc/cp-kafka:7.0.1
depends_on:
- zookeeper
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
clickhouse:
image: clickhouse/clickhouse-server:22.8
ports:
- "8123:8123"
- "9000:9000"
volumes:
- ./clickhouse-config.xml:/etc/clickhouse-server/config.xml
- ./clickhouse-data:/var/lib/clickhouse
ingestion:
build: ./ingestion
ports:
- "3000:3000"
environment:
KAFKA_BROKERS: kafka:9092
depends_on:
- kafka
processor:
build: ./processor
environment:
KAFKA_BROKERS: kafka:9092
CLICKHOUSE_URL: "http://clickhouse:8123"
depends_on:
- kafka
- clickhouse
grafana:
image: grafana/grafana:9.0.0
ports:
- "3001:3000"
volumes:
- ./grafana-provisioning:/etc/grafana/provisioning
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
7. PRIVACY COMPLIANCE FEATURES
GDPR Compliance Handler
// gdpr-handler.js
class GDPRHandler {
constructor() {
this.retentionPeriod = 90; // days
this.deletionQueue = [];
}
// Handle right to be forgotten
async deleteUserData(userId) {
const hashedId = this.hashUserId(userId);
// Mark for deletion in all systems
await this.markForDeletion(hashedId);
// Schedule actual deletion (after retention period)
this.scheduleDeletion(hashedId, this.retentionPeriod);
// Delete from session storage
localStorage.removeItem('rum_session_id');
}
async exportUserData(userId) {
const hashedId = this.hashUserId(userId);
// Query all systems for user data
const clickhouseData = await this.queryClickHouse(hashedId);
const kafkaData = await this.queryKafka(hashedId);
return {
userId: hashedId,
collectedData: {
events: clickhouseData,
rawStreams: kafkaData
},
exportDate: new Date().toISOString(),
retentionPeriod: this.retentionPeriod
};
}
scheduleDeletion(userId, days) {
const deletionDate = new Date();
deletionDate.setDate(deletionDate.getDate() + days);
// Add to deletion queue (persisted to DB)
this.deletionQueue.push({
userId,
scheduledDate: deletionDate,
status: 'pending'
});
}
}
8. OPTIMIZATION & BEST PRACTICES
Performance Optimization
// Performance-optimized RUM agent
class OptimizedRUMAgent {
constructor() {
this.beaconQueue = [];
this.useBeacon = navigator.sendBeacon !== undefined;
this.maxBatchSize = 5;
this.batchTimeout = 2000; // 2 seconds
}
sendEvent(event) {
// Add to queue
this.beaconQueue.push(event);
// Send immediately if critical
if (event.type === 'error' || event.type === 'navigation') {
this.flush();
}
// Batch non-critical events
else if (this.beaconQueue.length >= this.maxBatchSize) {
this.flush();
}
// Set timeout for batching
else if (!this.batchTimer) {
this.batchTimer = setTimeout(() => this.flush(), this.batchTimeout);
}
}
flush() {
if (this.beaconQueue.length === 0) return;
const data = JSON.stringify(this.beaconQueue);
this.beaconQueue = [];
if (this.useBeacon) {
navigator.sendBeacon('/api/v1/rum/batch', data);
} else {
// Fallback to fetch with keepalive
fetch('/api/v1/rum/batch', {
method: 'POST',
body: data,
keepalive: true
}).catch(() => {
// Store in IndexedDB for retry
this.queueForRetry(data);
});
}
clearTimeout(this.batchTimer);
this.batchTimer = null;
}
}
Key Considerations for Production:
-
Sampling Strategies:
- Static sampling: Fixed % (simple, predictable)
- Dynamic sampling: Adjust based on traffic volume
- Session-based: Ensure consistency within user sessions
- Page-type based: Different rates for different pages
-
Privacy Laws Compliance:
- CCPA/CPRA: "Do Not Sell" implementation
- GDPR: Right to delete, data portability
- HIPAA: For healthcare applications
- Cookie consent integration (OneTrust/Cookiebot)
-
Data Minimization:
- Collect only what's necessary
- Auto-expire data (90-day default)
- Anonymize before storage
- Separate PII from analytics data
-
Scalability:
- Use Kafka for backpressure handling
- ClickHouse for high-performance analytics
- Tiered storage (hot/cold data)
- Regional data centers for GDPR
-
Security:
- CORS restrictions
- Rate limiting per IP/session
- Input validation and sanitization
- Encryption at rest and in transit
- Regular security audits
-
Monitoring:
- Track sampling rates
- Monitor privacy gate effectiveness
- Alert on data volume anomalies
- Audit trail for data access
Quick Start Commands:
# Clone and setup
git clone <repo>
cd rum-pipeline
docker-compose up -d
# Initialize database
docker exec -it rum-clickhouse clickhouse-client -q "CREATE DATABASE rum"
# Deploy RUM agent to your site
<script src="https://your-cdn.com/rum-agent.js"
data-sample-rate="0.1"
data-privacy-level="strict"
async></script>
# Test ingestion
curl -X POST http://localhost:3000/api/v1/rum \
-H "Content-Type: application/json" \
-d '{"type":"page_load","url":"https://example.com","timing":{"loadTime":1200}}'
# Access Grafana at http://localhost:3001
# (Default credentials: admin/admin)
This pipeline provides:
- ✅ Privacy-first design with multiple filtering layers
- ✅ Scalable ingestion with Kafka batching
- ✅ Flexible sampling strategies
- ✅ GDPR/CCPA compliant data handling
- ✅ Real-time dashboards with Grafana
- ✅ Production-ready with alerting
- ✅ Cost-effective storage with TTL
Adjust sampling rates, privacy levels, and retention based on your specific compliance requirements and traffic patterns.