The user wants to build a Real User Monitoring (RUM) pipeline. This is a broad request that involves several components:
- Data Collection (Client-side): How to get data from the browser/app.
- Ingestion (Server-side/API): How to receive that data.
- Sampling: How to reduce the volume of data.
- Privacy Gates: How to remove PII (Personally Identifiable Information) and sensitive data.
- Storage: Where to put the data.
- Dashboards: How to visualize the data.
The user specifically asked for "sampling, privacy gates, and dashboards," so I need to focus heavily on these aspects, but I can't build a pipeline without addressing ingestion and storage at a high level.
Target Audience/Context: A developer or architect looking to build or understand a custom RUM system (or implement one using tools like OpenTelemetry, Kafka, Flink/Spark, and ClickHouse/Elasticsearch).
Key Components to Detail:
-
Architecture Overview: A high-level diagram description.
- Client -> Ingestion Endpoint -> Queue (Kafka) -> Stream Processor (Flink/Samza/Go microservice) -> Database -> Dashboard.
-
Sampling Strategies (The "Intelligence" of volume control):
- Head-based: Decision made at the client (simple, but drops errors too easily if not careful).
- Tail-based: Decision made at the server (harder, requires buffering, great for catching rare errors).
- Adaptive: Client adjusts based on volume.
- Implementation logic: How to write the code for a sampler (e.g., hash user ID, check ratio).
-
Privacy Gates (The "Compliance" layer):
- IP Masking: Truncating the last octet.
- PII Scrubbing: Regex for emails, credit cards, API keys.
- URL Query params: Stripping
?token=... or ?user_id=....
- Cookie handling: Ignoring specific cookies.
- Tools: Regex, specialized libraries (e.g., Google DLP API, or simple Go/Python scrubbers).
-
Data Model (What are we actually storing?):
- Core Web Vitals (LCP, FID, CLS).
- Resources (JS, CSS, Images).
- Errors (Stack traces).
- Long tasks.
-
Dashboards (The "Insights"):
- Performance: P75/P95/P99 of Load times.
- Geography: Map view.
- Error Tracking: Top errors by browser/OS.
- Funnel/Business: Conversion correlation.
-
Implementation Example (Code/Config):
- I should provide a conceptual implementation. A Go or Python snippet for the "Gate" logic is usually helpful. Or an OpenTelemetry Collector configuration. Let's stick to a generic "Pipeline Logic" approach using pseudocode or a specific tech stack like the OpenTelemetry Collector + ClickHouse + Grafana, as that's the modern standard.
Refining the "Build" aspect:
I shouldn't just list concepts. I should outline a project structure.
- Step 1: Ingestion & Sampling Logic.
- Step 2: The Privacy Gate (Code snippet).
- Step 3: Storage Choice.
- Step 4: Dashboard Queries.
Self-Correction/Edge Cases:
- Privacy: IP addresses are tricky. You need them for GeoIP but can't store them forever. Solution: Enrich GeoIP, then drop IP.
- Sampling: Errors should usually be sampled at 100% (don't drop errors!), while regular page views can be 1-10%.
Structure of the response:
- Architecture Diagram (Text-based).
- Phase 1: Intelligent Sampling (Client & Server).
- Phase 2: The Privacy Gate (The "Scrubber").
- Phase 3: Storage & Aggregation.
- Phase 4: Dashboarding Strategy.
- Tech Stack Recommendation.
Drafting the content:
- Sampling: Differentiate between Head (client) and Tail (server). Tail is better for performance anomalies, Head is better for cost. Let's recommend a hybrid: Head sampling for high volume, but error sampling forced to 100%.
- Privacy: Need a "allowlist" for query parameters (everything else gets dropped) vs a "blocklist" (regex replacement). Allowlist is safer.
- Dashboards: Mention specific charts. Histograms are better than averages.
Code Example:
Let's write a conceptual Python/Go snippet for the Stream Processor which handles the Privacy Gate and Sampling. This makes it concrete.
Tech Stack:
- Agent: OpenTelemetry (Web/JS).
- Gateway: OTel Collector / HAProxy / Nginx.
- Processing: Vector.dev or Flink or custom Go service.
- Storage: ClickHouse (standard for RUM/Observability).
- Viz: Grafana.
Let's write it out.
Building a Real User Monitoring (RUM) pipeline requires balancing data volume (cost) with data fidelity (insights) while strictly adhering to compliance laws (GDPR/CCPA).
Below is a comprehensive architecture and implementation guide for building a production-grade RUM pipeline.
1. High-Level Architecture
The pipeline flows from the client (browser/mobile) to your storage layer, passing through three critical gates.
[Client SDK] -> [Ingestion API] -> [Kafka/Queue] -> [Stream Processor] -> [Database] -> [Dashboard]
| |
v v
(Volume Control) (Privacy Gate)
2. Phase 1: Sampling (Volume Control)
You cannot store 100% of user sessions; it is cost-prohibitive and generates too much noise. Sampling allows you to capture a statistically significant subset of data.
Strategy: Head-Based Sampling (Client-Side)
This is the most efficient method. The SDK decides if a session is tracked before generating network traffic.
- Logic: Generate a random number. If < Sample Rate, track the session.
- Persistence: Store this decision in LocalStorage/SessionStorage so the user is consistently sampled throughout their journey.
Implementation (TypeScript/JavaScript SDK)
class RumSampler {
private sampleRate: number;
private isSampled: boolean | null = null;
private STORAGE_KEY = 'rum_sample_decision';
constructor(rate: number) {
// Rate is 0.0 to 1.0 (e.g., 0.1 is 10%)
this.sampleRate = rate;
this.init();
}
private init() {
const storedDecision = sessionStorage.getItem(this.STORAGE_KEY);
if (storedDecision) {
this.isSampled = storedDecision === 'true';
} else {
// Deterministic sampling based on randomness
this.isSampled = Math.random() < this.sampleRate;
sessionStorage.setItem(this.STORAGE_KEY, String(this.isSampled));
}
}
public shouldTrack(): boolean {
// Always track errors (Override sampling for errors)
// Or stick to strict sampling to save costs.
// Recommendation: Sample sessions, but if a session is picked, send all errors.
return this.isSampled === true;
}
}
// Usage
const sampler = new RumSampler(0.1); // 10% sampling
if (sampler.shouldTrack()) {
initializeRumAgent();
}
3. Phase 2: Privacy Gates (Compliance)
Privacy happens in two stages: Masking (Client-side) and Scrubbing (Server-side). Never trust the client to handle 100% of privacy.
A. Client-Side Masking (Input)
Before sending data, the SDK should obscure sensitive inputs.
- Text Masking: Replace text in input fields with
*** based on field names (e.g., type="password", name="credit_card").
- IP Anonymization: Set
dnt (Do Not Track) headers or explicitly request IP masking in the payload.
B. Server-Side Scrubbing (The "Gate")
This is the most critical layer. It inspects payloads for PII (Personally Identifiable Information) using Regular Expressions and Allow-lists.
Implementation (Node.js Stream Processor)
// privacy-gate.js
const SENSITIVE_KEYS = ['password', 'pwd', 'secret', 'token', 'api_key', 'ssn'];
const PII_REGEX = {
email: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
ssn: /\b\d{3}-\d{2}-\d{4}\b/g,
creditCard: /\b(?:\d[ -]*?){13,16}\b/g,
ipv4: /\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/g
};
function scrubPayload(payload) {
const jsonStr = JSON.stringify(payload);
// 1. Redact known sensitive keys
let cleanStr = jsonStr;
// 2. Regex Replacement (The "Gate")
// Replace matches with [REDACTED]
for (const [type, regex] of Object.entries(PII_REGEX)) {
cleanStr = cleanStr.replace(regex, `[REDACTED_${type.toUpperCase()}]`);
}
// 3. Specific Key Value scrubbing
// Deep traversal to null out specific keys
const data = JSON.parse(cleanStr);
recursiveScrub(data);
return data;
}
function recursiveScrub(obj) {
if (!obj || typeof obj !== 'object') return;
Object.keys(obj).forEach(key => {
if (SENSITIVE_KEYS.includes(key.toLowerCase())) {
obj[key] = '[FILTERED]';
} else if (typeof obj[key] === 'object') {
recursiveScrub(obj[key]);
}
});
}
module.exports = { scrubPayload };
4. Phase 3: Data Storage & Schema
RUM data is high-volume and "wide." Relational databases (Postgres/MySQL) usually struggle with the write throughput. Use a Columnar store or Time-Series DB.
Recommended Stack: ClickHouse (Best for aggregation/OLAP) or Elasticsearch.
The Schema (Simplified):
timestamp: DateTime
session_id: UUID (Links events together)
user_id: String (Anonymous or Hashed ID)
event_type: Enum (PageView, Error, LongTask, Resource)
web_vitals: Map(String, Float) (LCP, FID, CLS)
url: String
country_code: String (Derived from IP at ingestion)
5. Phase 4: Dashboards (Visualizing Insights)
The goal is to move from "Data" to "User Experience Scores."
Dashboard 1: Performance (Web Vitals)
Monitor the "Core Web Vitals" which impact SEO and UX.
- Graphs:
- LCP (Largest Contentful Paint): Histogram (P50, P75, P95). Goal: < 2.5s.
- FID (First Input Delay): P95. Goal: < 100ms.
- CLS (Cumulative Layout Shift): P75. Goal: < 0.1.
- Breakdown: Group by Browser (Chrome vs Safari) and Connection Type (4G vs Wifi).
Dashboard 2: Error Tracking
- Top Error Messages: Bar chart of frequent stack traces.
- Error Rate: (Total Errors / Total Sessions) * 100.
- Impact: Which pages have the highest crash rates?
Dashboard 3: Business Flow (Funnel)
Correlate performance with business outcomes.
- Conversion Correlation: "Did users with LCP > 4s convert less than users with LCP < 2s?"
- Rage Clicks: Visualize where users click repeatedly in frustration.
6. Implementation Checklist
- Ingestion API: A lightweight API (Go or Node) that accepts JSON, validates auth, pushes to Kafka.
- Stream Processor: A consumer (Flink, Kafka Streams, or simple Node worker) that:
- Runs the
privacy-gate script.
- Enriches data (GeoIP lookup from IP).
- Drops "bot" traffic (User-Agent checks).
- Query Layer: A backend service that translates dashboard queries into SQL (ClickHouse) queries.
- Alerting: Set thresholds (e.g., "If P95 LCP > 5s for 5 mins, alert Slack").
Recommended Open Source Tools
If you don't want to write everything from scratch: