Data Modeling for Analytics and AI Together
For most of the last decade, data modeling for analytics meant one thing: dimensional modeling. Star schemas, fact tables, slowly changing dimensions. Kimball. Inmon. dbt. The discipline was mature, the patterns were established, the tooling was excellent.
Then AI arrived as a first-class application requirement, and data teams found themselves with a new problem: the models optimized for dashboards and SQL queries don't always work for model training and feature engineering. Yet maintaining two separate data worlds—one for analytics, one for AI—is expensive and leads to the same data being modeled inconsistently in two places.
This article explores how to design data models that genuinely serve both analytics and AI without sacrificing either.
The Tension Between Analytics and AI Data Needs
Analytics and AI have fundamentally different data consumption patterns:
Analytics needs:
- Aggregated metrics (revenue by product, DAU by cohort)
- Slowly changing dimensions (current customer status)
- Optimized for SQL queries and BI tools
- Consistent definitions across dashboards
- Human-readable column names and business logic
AI/ML needs:
- Raw event sequences (what did the user do and in what order?)
- Point-in-time correct feature snapshots (what was true at event time?)
- Wide tables with many features per entity
- Numerical representations of categorical data
- Historical data with no label leakage
The good news is that with thoughtful modeling, you can satisfy both from a single source of truth.
The Three-Layer Architecture
The most successful approach separates concerns into three distinct layers:
Layer 1: Source Layer (Raw, Immutable)
Raw data landed from source systems, never transformed. This is the permanent record. Analytics and AI both read from here as their starting point.
-- source: raw event stream, never modified
CREATE TABLE raw.user_events (
event_id UUID NOT NULL,
user_id VARCHAR NOT NULL,
event_type VARCHAR NOT NULL,
event_timestamp TIMESTAMP NOT NULL,
properties JSONB,
session_id VARCHAR,
device_type VARCHAR,
inserted_at TIMESTAMP DEFAULT NOW()
);
Layer 2: Staging Layer (Cleaned, Typed)
Light transformations only: casting types, renaming columns, handling nulls. No business logic. Both analytics and ML models read from staging.
-- dbt staging model: stg_user_events.sql
SELECT
event_id,
user_id,
event_type,
event_timestamp::TIMESTAMP WITH TIME ZONE AS event_timestamp,
COALESCE(properties->>'page', 'unknown') AS page,
COALESCE(session_id, 'no_session') AS session_id,
LOWER(COALESCE(device_type, 'unknown')) AS device_type
FROM {{ source('raw', 'user_events') }}
WHERE event_id IS NOT NULL
AND user_id IS NOT NULL
AND event_timestamp > '2022-01-01'
Layer 3: Split Into Analytics Models and Feature Models
Here's where the two paths diverge—and that's okay, as long as they're built from the same staging layer.
Analytics path: dimensional models
-- dbt model: fct_daily_user_activity.sql (for analytics)
SELECT
DATE_TRUNC('day', event_timestamp) AS activity_date,
user_id,
COUNT(*) AS total_events,
COUNT(DISTINCT session_id) AS session_count,
SUM(CASE WHEN event_type = 'purchase' THEN 1 ELSE 0 END) AS purchase_count,
SUM(CASE WHEN event_type = 'purchase'
THEN CAST(properties->>'revenue' AS FLOAT) ELSE 0 END) AS revenue
FROM {{ ref('stg_user_events') }}
GROUP BY 1, 2
AI/ML path: feature tables
-- dbt model: feat_user_rolling_features.sql (for ML)
-- Point-in-time correct rolling features for model training
SELECT
e.user_id,
e.event_timestamp AS feature_timestamp,
-- Features use only data available at event_timestamp
COUNT(*) OVER (
PARTITION BY e.user_id
ORDER BY e.event_timestamp
RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW
) AS events_7d,
COUNT(DISTINCT s.session_id) OVER (
PARTITION BY e.user_id
ORDER BY e.event_timestamp
RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW
) AS sessions_7d,
SUM(CASE WHEN e.event_type = 'purchase' THEN 1 ELSE 0 END) OVER (
PARTITION BY e.user_id
ORDER BY e.event_timestamp
RANGE BETWEEN INTERVAL '30 days' PRECEDING AND CURRENT ROW
) AS purchases_30d
FROM {{ ref('stg_user_events') }} e
The Entity-Centric Model for AI
One pattern that works especially well for AI is the entity-centric model: every feature is attached to an entity (user, product, document) at a specific point in time. This directly maps to how feature stores organize data.
-- Entity-centric user feature model
CREATE TABLE features.user_state (
user_id VARCHAR NOT NULL,
snapshot_timestamp TIMESTAMP NOT NULL,
-- Activity features
events_7d INTEGER,
events_30d INTEGER,
sessions_7d INTEGER,
-- Commerce features
purchases_30d INTEGER,
revenue_30d DECIMAL(12,2),
avg_order_value DECIMAL(10,2),
days_since_last_purchase INTEGER,
-- Engagement features
content_views_7d INTEGER,
search_queries_7d INTEGER,
-- Derived features
purchase_frequency_score FLOAT, -- engineered
engagement_tier VARCHAR, -- binned
PRIMARY KEY (user_id, snapshot_timestamp)
);
This table structure is immediately consumable by:
- A feature store (load it as an offline store)
- A training pipeline (join to labeled events with point-in-time correctness)
- A dashboard (query latest snapshot per user for current state reports)
Handling Slowly Changing Dimensions in AI
Slowly changing dimensions (SCDs) are well-understood in analytics—Type 1 (overwrite), Type 2 (version history), Type 3 (current + previous). For AI, Type 2 SCDs are almost always required: you need to know what the customer's tier was at the time of a specific event, not what it is today.
-- SCD Type 2 for customer tier
CREATE TABLE dimensions.customer_tier_history (
surrogate_key UUID DEFAULT gen_random_uuid() PRIMARY KEY,
customer_id VARCHAR NOT NULL,
tier VARCHAR NOT NULL, -- 'free', 'pro', 'enterprise'
valid_from TIMESTAMP NOT NULL,
valid_to TIMESTAMP, -- NULL means current
is_current BOOLEAN NOT NULL DEFAULT TRUE
);
-- Point-in-time correct join for ML training
SELECT
e.event_id,
e.customer_id,
e.event_timestamp,
t.tier AS customer_tier_at_event_time
FROM training_events e
JOIN dimensions.customer_tier_history t
ON e.customer_id = t.customer_id
AND e.event_timestamp >= t.valid_from
AND (e.event_timestamp < t.valid_to OR t.valid_to IS NULL)
Semantic Layer: Shared Definitions
The biggest win in serving both analytics and AI from one platform is the semantic layer: a central place where business metric definitions live, reusable across dashboards and feature pipelines.
dbt Metrics (and the dbt Semantic Layer) allow you to define a metric once:
# dbt metrics: metrics.yml
metrics:
- name: revenue_30d
label: 30-Day Revenue
model: ref('fct_daily_revenue')
description: Total revenue over trailing 30 days
type: sum
type_params:
measure: revenue
filter: |
{{ Dimension('metric_time') }} >= dateadd('day', -30, current_date())
dimensions:
- product_category
- customer_tier
- country
The same revenue_30d definition now powers:
- A Looker/Metabase dashboard metric
- An ML feature ("user's revenue contribution over last 30 days")
- A business alert ("revenue is down 20% vs. last week")
This single source of business logic eliminates the inconsistency where a dashboard shows one number and an ML model was trained on a differently-calculated version of the same concept.
Data Model Testing for Analytics and AI
Testing data models that serve both analytics and AI requires tests at multiple levels:
# dbt tests for analytics integrity
models:
- name: fct_daily_user_activity
columns:
- name: user_id
tests:
- not_null
- relationships:
to: ref('dim_users')
field: user_id
- name: activity_date
tests:
- not_null
- name: total_events
tests:
- not_null
- accepted_range:
min_value: 0
- name: feat_user_rolling_features
tests:
# Custom test: No data leakage (features only use past data)
- no_future_data_leakage:
event_timestamp_column: feature_timestamp
feature_columns: [events_7d, sessions_7d, purchases_30d]
# Python test: validate ML features
def test_no_label_leakage(feature_df, label_df):
"""
Ensure feature timestamps are always before label timestamps
for each training example.
"""
merged = feature_df.merge(label_df, on="user_id")
leakage = merged[merged["feature_timestamp"] >= merged["label_timestamp"]]
assert len(leakage) == 0, f"Found {len(leakage)} examples with data leakage"
def test_feature_distribution(feature_df, reference_df, threshold=0.1):
"""
KS test: current feature distribution shouldn't drift more than threshold from reference.
"""
from scipy.stats import ks_2samp
for col in ["events_7d", "sessions_7d", "purchases_30d"]:
stat, p_value = ks_2samp(feature_df[col], reference_df[col])
assert p_value > threshold, f"Feature {col} has drifted significantly (p={p_value:.4f})"
Key Takeaways
- Three-layer architecture works: Source → Staging → (Analytics models + Feature models). Both branches built from the same clean staging layer.
- Entity-centric feature tables bridge analytics and AI: Snapshots of entity state at points in time serve both pattern's needs.
- Type 2 SCDs are required for AI correctness: You need historical dimension values for point-in-time correct training data.
- Semantic layer unifies business logic: Define metrics once, use them in dashboards and feature pipelines alike.
- Test both analytics invariants and ML-specific properties: Data leakage tests and distribution checks are as important as not-null checks.
FAQ
Q: Should analytics engineers and ML engineers share a dbt repo? A: Yes, for most teams. The shared staging models are the critical integration point. Separating repos creates divergence at exactly the layer where consistency matters most.
Q: How do I handle features that analytics doesn't care about (like entity embeddings)? A: Keep them in your feature store or a dedicated ML feature table. The shared dbt repo handles structured features; specialized infrastructure handles embeddings and vectors.
Q: What's the right grain for a feature table? A: Entity + timestamp. One row per entity per snapshot time. This maps directly to feature store semantics and enables point-in-time correct joins.