1. Analyze the Request:
* Goal: Compose a "unified telemetry lake schema."
* Scope: Must cover three specific domains:
* UX Events (Frontend/User interactions).
* API Traces (Backend service calls/distributed tracing).
* Model Outputs (ML/AI inference results).
* Key Concept: "Unified" implies a single, consistent schema (or a set of schemas) that allows for joining and correlating data across these disparate sources. "Lake" implies raw storage (e.g., Parquet/Avro on S3) but usually suggests a structure that supports efficient querying (like a Table format).
-
Deconstruct the Domains & Identify Commonalities:
-
UX Events: High volume, session-based, user-centric, qualitative data (clicks, views), client-side metadata (browser, OS).
-
API Traces: High volume, request/response based, system-centric, latency, status codes, distributed context (trace IDs, span IDs).
-
Model Outputs: Structured predictions, confidence scores, model versions, input embeddings/features, latency.
-
Common Keys (The "Glue"):
- Time (
event_time is crucial).
- Identity (
user_id, session_id, request_id/trace_id).
- Context (
environment, app_version, deployment_id).
- Schema evolution management.
-
Determine the Schema Strategy:
- Option A: Single Giant Table. Bad idea. Too sparse, inefficient querying, difficult to manage access control.
- Option B: Completely Separate Tables. Good for silos, bad for correlation.
- Option C: Star Schema / Entity-Centric. Good, but maybe too complex for a raw telemetry lake definition.
- Option D: "One Big Table" with Type Polymorphism (Entity-Attribute-Value style) or Structs.
- Selected Strategy: A Hybrid Approach. A core "Event" schema (the header) containing universal fields, followed by specific payload structs/unions for the domain-specific data. This allows storing them in the same logical table (or bucket structure) while keeping the physical storage efficient (columnar formats handle nulls/sparse structs well).
-
Drafting the Schema (Iterative Process):
-
Refining and Structuring for "Lake" Compatibility:
- The schema should be defined in a technology-agnostic way (like Proto3, Avro, or just a clear JSON/SQL representation). I will use a clear, nested JSON-like structure or Apache Iceberg/Delta Lake style definition because those are industry standards for "Lakes."
- Crucial addition: Correlation IDs. The user requested a unified schema. The value prop is joining UX to API to Model.
- Refining
event_type: Instead of just a string, maybe use specific fields that are nullable?
- Decision: Use a "Root" schema with optional structs. This is cleaner for SQL engines (e.g.,
WHERE api.status_code = 500).
-
Constructing the Output:
- Introduction: Define the philosophy (Wide Event Model).
- The Schema (Pseudo-SQL/JSON): Break it down into sections.
BaseEvent (The mandatory fields).
Context (Who/Where).
Payloads (The specific domains).
- The "Golden Thread" (Trace Context): Explain how to link them.
- Implementation Details: Mention partitioning (by date/hour) and file formats (Parquet).
-
Self-Correction/Review during drafting:
- Critique: Is
properties map<string, string> enough?
- Correction: No, for Model outputs, we need strong typing or complex JSON. I should specify
model_output as a flexible JSON/Struct type.
- Critique: Should I include specific LLM fields?
- Correction: The prompt asks for "Model Outputs," which usually implies LLMs these days but could be regression. I will include token usage as it's critical for cost tracking in modern lakes.
-
Final Polish: Ensure the names are snake_case, types are clear, and the logic of correlation is obvious. Add a section on "Example Queries" to demonstrate utility.
(Self-Correction during drafting the TraceContext): Make sure to emphasize that the UX layer must generate the trace_id and pass it down to the API layer for true unification. This is a common failure point in telemetry implementations.
- Final Output Generation (This matches the provided good response).
A Unified Telemetry Lake must move beyond simply dumping logs into a bucket. It requires a "Wide Event" architecture where context is denormalized, and high-cardinality IDs (Trace IDs, Session IDs) are first-class citizens.
Here is a comprehensive schema design using a Polymorphic Envelope pattern. This design is compatible with modern columnar formats (Parquet, Apache Iceberg, Delta Lake) and allows for efficient querying across UX, API, and ML domains.
1. The Schema Philosophy
To "unify" these three distinct sources, we treat every row as an Event. The schema consists of a Common Header (immutable metadata) and a Polymorphic Payload (domain-specific details).
- UX Events: Focus on Who, What, Where (DOM path, A/B test group).
- API Traces: Focus on Latency, Dependency, Status (HTTP codes, DB calls).
- Model Outputs: Focus on Fidelity, Cost, Version (Tokens, probabilities, model ID).
2. The Unified Schema Definition (Pseudo-SQL/Parquet)
This schema assumes a columnar storage format where "Nullable" structs are cheap (skipped during scanning if empty).
CREATE TABLE telemetry_lake (
-- ===========================================================
-- SECTION 1: COMMON ENVELOPE (The "Golden Nuggets")
-- ===========================================================
event_id STRING NOT NULL, -- UUID for this specific event
event_timestamp TIMESTAMP NOT NULL, -- ISO 8601 / Unix Epoch (UTC)
event_type STRING NOT NULL, -- 'ux_interaction', 'api_request', 'model_inference'
event_name STRING NOT NULL, -- 'click_submit', 'POST /users', 'gpt-4-completion'
-- Correlation Vectors (The glue between domains)
trace_id STRING, -- Distributed Trace ID (W3C Trace Context)
span_id STRING, -- Specific ID for this operation
parent_span_id STRING, -- Links UI click -> API call -> Model call
session_id STRING, -- User session scope
-- Actor Context
user_id STRING, -- Stable user UUID (hashed if PII)
anonymous_id STRING, -- Cookie/Device ID (pre-login)
team_tenant_id STRING, -- B2B multi-tenancy context
-- Environment Context
app_version STRING, -- Semantic version (e.g., v1.2.3)
environment STRING, -- 'production', 'staging', 'canary'
deployment_id STRING, -- K8s Pod ID / Lambda Version
-- ===========================================================
-- SECTION 2: DOMAIN PAYLOADS (Mutually Exclusive Groups)
-- ===========================================================
-- A. UX / Frontend Specifics
ux_context STRUCT<
page_route STRING, -- React/Vue route path (e.g., /settings/:id)
referrer_url STRING,
dom_xpath STRING, -- Specific element interacted with
client_device_type STRING, -- 'mobile', 'desktop', 'tablet'
client_os STRING,
client_browser STRING,
viewport_width INT,
ab_test_groups MAP<STRING, STRING>,-- e.g., {'checkout_flow': 'variant_b'}
performance_metrics STRUCT< -- Web Vitals linked to this UX event
fcp_ms FLOAT, -- First Contentful Paint
lcp_ms FLOAT -- Largest Contentful Paint
>
>,
-- B. API / Infrastructure Traces
api_context STRUCT<
http_method STRING, -- GET, POST, PUT, DELETE
http_path STRING, -- Raw path
http_route STRING, -- Templated path (e.g., /users/:id)
status_code INT,
request_size_bytes INT,
response_size_bytes INT,
latency_ms FLOAT, -- End-to-end duration
-- Service Dependency Graph
service_name STRING, -- 'billing-service', 'gateway'
downstream_calls ARRAY<STRUCT<
service_name STRING,
latency_ms FLOAT,
status_code INT
>>,
-- Error Handling
error_code STRING, -- Application specific error code
error_stack_trace STRING
>,
-- C. Model / AI Outputs
model_context STRUCT<
model_id STRING, -- 'gpt-4-turbo', 'stable-diffusion-v1.6'
model_fingerprint STRING, -- Specific checkpoint hash
model_version STRING,
-- Input/Output Metrics
prompt_tokens INT,
completion_tokens INT,
total_tokens INT,
input_cost_usd FLOAT, -- Calculated cost at inference time
output_cost_usd FLOAT,
-- Quality & Safety
probability_score FLOAT, -- Confidence score
finish_reason STRING, -- 'stop', 'length', 'error'
safety_flags MAP<STRING, BOOLEAN>,-- {'hate_speech': false, 'violence': true}
-- RAG Context (Retrieval Augmented Generation)
rag_source_ids ARRAY<STRING> -- IDs of documents retrieved to ground answer
>,
-- ===========================================================
-- SECTION 3: UNIFIED METADATA
-- ===========================================================
ingestion_timestamp TIMESTAMP, -- When it hit the data lake
source_system STRING, -- 'web-sdk', 'mobile-sdk', 'otel-collector', 'langfuse'
-- Flexible Bag for misc data (Avoid querying this heavily)
meta MAP<STRING, STRING>
)
PARTITIONED BY (
date_part DATE, -- Hourly or Daily partitioning
environment STRING
);
3. The Correlation Strategy (How it works)
The power of this lake comes from the Trace ID Propagation. Here is how the data flows through the schema:
Step 1: UX Interaction (Frontend)
A user clicks "Generate Summary".
- Event Type:
ux_interaction
- Event Name:
click_generate
- Trace ID: Generated by frontend (e.g.,
trace-abc-123).
- UX Context:
{ dom_xpath: "...", ab_test_groups: {"summarizer": "v2"} }
- API/Model Context: NULL
Step 2: API Request (Backend)
The frontend calls POST /api/summarize passing the trace-abc-123 in the request headers.
- Event Type:
api_request
- Event Name:
POST /summarize
- Trace ID:
trace-abc-123 (Inherited)
- Parent Span ID: Links to the UX click event.
- API Context:
{ latency_ms: 1200, status_code: 200 }
- Model Context: NULL
Step 3: Model Inference (Internal Service)
The API calls an internal Python service or External LLM provider.
- Event Type:
model_inference
- Event Name:
gpt-4-summary
- Trace ID:
trace-abc-123 (Inherited)
- Model Context:
{ prompt_tokens: 100, completion_tokens: 50, probability_score: 0.88 }
4. Query Patterns
Because this is a unified schema, you can write "Vertical" queries that cross domains.
Example 1: Debugging Latency (UX + API)
"Show me users who experienced slow page loads (>3s) on the checkout page and which API traces were responsible."
SELECT user_id, ux_context.page_route, api_context.http_route, api_context.latency_ms
FROM telemetry_lake
WHERE date_part = CURRENT_DATE
AND ux_context.page_route LIKE '/checkout%'
AND api_context.latency_ms > 3000
AND trace_id IS NOT NULL;
Example 2: Cost & Quality Attribution (Model + UX)
"Find all chat sessions where the LLM returned a 'safety_violation' and check if the user churned (closed the window) immediately after."
SELECT
m.event_id,
m.model_context.safety_flags,
u.ux_context.page_route as exit_page
FROM telemetry_lake m
JOIN telemetry_lake u
ON m.trace_id = u.trace_id
AND u.event_type = 'ux_interaction'
AND u.ux_context.dom_xpath LIKE '%close_button%' -- Simplified exit logic
WHERE m.model_context.safety_flags['hate_speech'] = true;
5. Implementation Best Practices
- Column Compaction: Since 90% of your volume will be UX events, the
model_context and api_context columns will be mostly null. Use Apache Iceberg or Delta Lake with Z-Ordering on event_type to ensure queries for "Model Outputs" do not scan the entire UX history.
- PII Scrubbing: Ensure
user_id and request_headers are hashed or stripped by an OTEL collector or Kafka stream processor before writing to the lake.
- Nested Structures: Using
STRUCT types (as shown in the SQL) is vastly more performant than storing JSON strings, as query engines (Trino, Spark, BigQuery) can prune columns effectively.