Hi There! Did you enjoy any of my projects? I am always open for mentorship and/or contract work. You can reach me here.
Home

Self-hosted dbt Charts

A distilled guide to wiring Ridge regression and saturation curves into dbt, rendering dashboards to static HTML, and deploying to Vercel without a backend
Published 4 November 2026

With most of the analytics world's attention on Looker, Tableau & PowerBI; a smaller initiative is growing slowly, but surely. It is called: dbt Charts!

For a long time the type of constraints the top 3 gave us was more enforced as there were no really other options with a sizeable community behind them. I used Observable before and also even contributed to their codebase, but it just felt too fringe and not really what any of the companies I worked at used.

In addition to that Plotly and others started to make waves in the Python-world, but just felt less responsive.

I took dbt Charts for a spin and came up with this demo application deployed on Vercel: dbtcharts.vercel.app

dbt Charts demo — Retail Media Analytics Dashboards on Vercel
Retail Media Analytics Dashboards — static export built with dbt Charts, hosted on Vercel

Most analytics pipelines are bigger than they need to be. A warehouse, a transformation layer, a BI tool licence, a dashboard server, an ML platform. By the time you've assembled all the pieces, you're maintaining infrastructure instead of answering business questions.

This project takes the other path: DuckDB for the warehouse (a single file, no server), dbt for transformations (including Python ML models), and dbt Charts to render everything to static HTML that deploys to a CDN. The whole stack runs on a laptop, ships in one git push, and costs nothing to host.

It's built around a retail media scenario — 12 campaigns, three channels, 90 days of data — but the patterns transfer directly to any domain where you're combining SQL transformations with predictive modelling and need to show the results to someone who doesn't live in a notebook.

What we're building

Three dashboards, one pipeline:

Campaign Performance — ROAS, CTR, spend and conversions per campaign, filterable by brand and channel. The kind of board a media buyer opens every morning.

Sales Forecast — 90 days of historical actuals plus a 30-day Ridge regression forecast with confidence bands, generated entirely inside dbt as a Python model.

Promotional Allocation Simulator — a logarithmic saturation model fitted per channel that answers: if we shifted budget from Search to Off-Site, what would projected sales look like? Five scenarios, three channels, one table.

The data layer: synthetic but realistic

The seed data is generated by a Python script. It doesn't produce random numbers — it produces numbers with the statistical signatures real retail media data has: Sponsored Search with high CTR and moderate ROAS, Off-Site with higher ROAS variance, Display with low conversion rates but volume. The downstream ML models need signal to learn from, so the data has to behave.

generate_seeds.py (excerpt)
CHANNEL_PROFILES = {
    "Sponsored Search": {"ctr_mean": 0.45, "ctr_std": 0.08, "roas_mean": 1.4, "roas_std": 0.5},
    "Display":          {"ctr_mean": 0.15, "ctr_std": 0.04, "roas_mean": 0.9, "roas_std": 0.4},
    "Off-Site":         {"ctr_mean": 0.25, "ctr_std": 0.07, "roas_mean": 2.1, "roas_std": 0.9},
}

for _, campaign in campaigns.iterrows():
    profile = CHANNEL_PROFILES[campaign["channel"]]
    for day in date_range:
        ctr   = max(0, np.random.normal(profile["ctr_mean"], profile["ctr_std"]))
        roas  = max(0, np.random.normal(profile["roas_mean"], profile["roas_std"]))
        spend = daily_budget * np.random.uniform(0.85, 1.15)
        rows.append({"date": day, "campaign_id": campaign["id"],
                     "spend": spend, "attributed_sales": spend * roas, "ctr": ctr})

Three seeds: dim_campaigns (12 rows of metadata), fct_media_performance (~430 rows of daily impressions/clicks/spend), fct_conversions (~430 rows of daily conversions/sales/ROAS).

The dbt layer: SQL first, Python where it matters

The staging layer is boring on purpose. Three views that type-cast and lightly clean the seeds. No business logic. The interesting work happens in the mart layer.

mart_campaign_performance is a SQL model — a join across the three staging views with cumulative window functions so the dashboard charts can show running totals without re-aggregating at query time:

models/marts/mart_campaign_performance.sql (excerpt)
SELECT
    p.date,
    p.campaign_id,
    c.campaign_name,
    c.brand,
    c.channel,
    p.spend,
    cv.attributed_sales,
    ROUND(cv.attributed_sales / NULLIF(p.spend, 0), 4)   AS roas,
    p.ctr,
    ROUND(p.spend / NULLIF(p.clicks, 0), 4)              AS cpc,
    cv.conversions,
    SUM(p.spend) OVER (
        PARTITION BY p.campaign_id ORDER BY p.date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    )                                                     AS cumulative_spend
FROM stg_media_performance p
LEFT JOIN stg_campaigns     c  ON p.campaign_id = c.campaign_id
LEFT JOIN stg_conversions   cv ON p.campaign_id = cv.campaign_id AND p.date = cv.date

Python inside dbt: Ridge regression for sales forecasting

This is where it gets interesting. dbt supports Python models natively — .py files that sit alongside .sql models in the same DAG, with the same lineage tracking and dependency resolution.

A Python model receives a dbt context object and returns a DataFrame. dbt materialises that DataFrame as a table in DuckDB. No separate ML pipeline. No orchestrator. Just a function.

models/marts/fct_sales_prediction.py
def model(dbt, session):
    dbt.config(materialized="table")

    # Pull from the upstream SQL mart — standard dbt.ref()
    perf = dbt.ref("mart_campaign_performance").df()

    # Aggregate to daily totals
    daily = (
        perf.groupby("date", as_index=False)
        .agg(total_spend=("spend", "sum"), total_sales=("attributed_sales", "sum"))
        .sort_values("date")
    )

    # Feature engineering: spend, log-spend, day-of-week (cyclical), week-of-year
    def make_features(dates, spend):
        dates   = pd.DatetimeIndex(dates)
        day_num = (dates - dates.min()).days
        dow     = dates.dayofweek
        return pd.DataFrame({
            "spend":     spend.values,
            "log_spend": np.log1p(spend.values),
            "day_num":   np.array(day_num),
            "dow_sin":   np.sin(2 * np.pi * np.array(dow) / 7),
            "dow_cos":   np.cos(2 * np.pi * np.array(dow) / 7),
        })

    X = make_features(daily["date"], daily["total_spend"])
    y = daily["total_sales"].values

    # Ridge regression in a sklearn pipeline
    pipe = Pipeline([
        ("scaler", StandardScaler()),
        ("ridge",  Ridge(alpha=1.0)),
    ])
    pipe.fit(X, y)

    # 30-day forward forecast using EWM-extrapolated spend
    future_dates = pd.date_range(daily["date"].max() + timedelta(days=1), periods=30)
    future_spend = daily["total_spend"].tail(30).ewm(span=14).mean().iloc[-1]
    X_future     = make_features(future_dates, pd.Series([future_spend] * 30))

    # Confidence bands: ±1.5 σ of in-sample residuals
    resid_std    = (y - pipe.predict(X)).std()
    forecast     = pipe.predict(X_future)

    # Return historical + forecast rows as one DataFrame
    # dbt materialises this as a DuckDB table
    ...

Ridge was chosen deliberately over gradient boosted trees or neural nets: it's regularised (safe on 90 rows), fast, and its coefficients are human-readable. The alpha=1.0 penalty keeps it from overfitting to the weekly seasonality noise. The confidence band is ±1.5σ of in-sample residuals — wide enough to be honest, narrow enough to be useful.

Python inside dbt: log saturation curves for budget allocation

The allocation model fits a logarithmic diminishing-returns curve per channel:

Sales = α · ln(1 + β · Spend)

As spend increases, each additional dollar yields less. α controls the ceiling;β controls how quickly you get there. scipy.optimize.curve_fit estimates both from 90 days of daily channel data.

models/marts/fct_promotional_allocation.py (excerpt)
def _log_response(spend, alpha, beta):
    return alpha * np.log1p(beta * np.maximum(spend, 0))

def _fit_channel(spend, sales):
    try:
        popt, _ = curve_fit(
            _log_response, spend, sales,
            p0=[sales.max(), 1.0 / (spend.mean() + 1e-6)],
            bounds=([0, 1e-9], [np.inf, np.inf]),
        )
        return float(popt[0]), float(popt[1])
    except Exception:
        # Graceful fallback: linear ratio if curve_fit diverges
        return float(np.median(sales / (spend + 1e-9))), 1.0

# Scenarios: each is a multiplier on baseline spend per channel
SCENARIOS = [
    (0, "Baseline",       {"Sponsored Search": 1.00, "Display": 1.00, "Off-Site": 1.00}),
    (1, "Search Boost",   {"Sponsored Search": 1.20, "Display": 0.90, "Off-Site": 0.90}),
    (2, "Display Boost",  {"Sponsored Search": 0.85, "Display": 1.30, "Off-Site": 0.85}),
    (3, "Off-Site Boost", {"Sponsored Search": 0.90, "Display": 0.85, "Off-Site": 1.25}),
    (4, "Even Scale-Up",  {"Sponsored Search": 1.10, "Display": 1.10, "Off-Site": 1.10}),
]

# For each scenario × channel: apply multiplier, run through fitted curve,
# compare to baseline projected sales → compute lift and ROAS

The result is a table with 15 rows (5 scenarios × 3 channels), each with baseline spend, scenario spend, projected sales, sales lift, and projected ROAS. The whole thing runs in under a second on 90 days of data.

dbt Charts: YAML-driven dashboards that output HTML

dbt Charts (dct) is the rendering layer. You write a YAML board definition that references named queries and specifies chart types — bar, line, KPI tile, table.dct render runs those queries against DuckDB and outputs a self-contained HTML file. No server needed to view it.

charts/allocation_simulator.yml (excerpt)
queries:
  scenario_totals:
    sql: |
      SELECT
        scenario_name,
        ROUND(SUM(projected_sales), 0)   AS projected_sales,
        ROUND(SUM(projected_sales) / NULLIF(SUM(scenario_spend), 0), 2) AS projected_roas
      FROM fct_promotional_allocation
      GROUP BY scenario_name
      ORDER BY projected_roas DESC

charts:
  bar_proj_sales:
    type: bar
    title: Projected Total Sales by Scenario
    query: scenario_totals
    x: scenario_name
    y: projected_sales
    y_label: "Projected Sales ($)"

  bar_channel_lift:
    type: bar
    title: Sales Lift vs Baseline ($) by Channel per Scenario
    query: channel_lift
    x: channel
    y: sales_lift
    color: scenario_name
    style:
      orientation: horizontal
      axis_y:
        scale:
          continuous:
            domain: [-2500, 2500]

rows:
  - cols: [bar_proj_sales, bar_proj_roas]
  - bar_channel_lift
  - detail_table

The key design decision: variables with input: select are interactive indct serve (which runs queries live against DuckDB) but fixed in a static export. For a static site, you either pre-render with a default variable value (dct render ... --var "scenario=Off-Site Boost") or redesign charts to show all data without filtering. The allocation board uses the latter — a full comparison table that shows all four scenarios at once.

Deploying to Vercel: the static export trick

The public/ directory contains pre-rendered HTML files committed to git.vercel.json points Vercel at that directory with no build command:

vercel.json
{
  "outputDirectory": "public",
  "framework": null,
  "buildCommand": "",
  "installCommand": ""
}

Every git push to main triggers a Vercel deployment that serves the new HTML files directly from the CDN. Zero cold starts, zero build time, zero runtime dependencies. The dashboards load in under 200ms globally.

A post-processing shell script handles the pipeline after every dbt run:

scripts/render-site.sh (outline)
# 1. Render boards to HTML
dct render charts/campaign_performance.yml charts/sales_forecast.yml \
  --format html --output public/boards/{stem}.html

dct render charts/allocation_simulator.yml \
  --format html --output public/boards/allocation_simulator.html \
  --var "scenario=Off-Site Boost"

# 2. Post-process: inject sponsor bar, auth check, analytics, timestamp
python3 - "$OUTPUT_DIR" "$TIMESTAMP" <<'PYEOF'
...
PYEOF

# 3. Stamp timestamp in index.html
# 4. git add public/ && git commit && git push

Auth without a backend

The site is behind a login page, but there's no auth service, no session store, no JWT library. Just two Vercel serverless functions and a cookie.

api/login.js
export default function handler(req, res) {
  if (req.method !== 'POST') return res.status(405).end();

  const { username, password } = req.body;
  const validUser = process.env.LOGIN_USER     ?? 'demo';
  const validPass = process.env.LOGIN_PASSWORD ?? 'demo123';

  if (username === validUser && password === validPass) {
    res.setHeader('Set-Cookie',
      'dct_session=1; Path=/; SameSite=Lax; Secure; Max-Age=86400');
    return res.status(200).json({ ok: true });
  }
  return res.status(401).json({ error: 'Invalid credentials' });
}

Every board page has a one-liner inline script that checks for the cookie before the page renders:

inline script (each board page)
<script>
  if (!document.cookie.split(';').some(c => c.trim().startsWith('dct_session='))) {
    window.location.replace('/login.html');
  }
</script>

Credentials live in Vercel environment variables. Each client deployment gets its own. The demo deployment shows them on the login page — it's intentional, it's a demo.

This is client-side auth enforcement, not server-side. A determined person can bypass it by setting the cookie manually in DevTools. For a demo site with synthetic data, that's fine. For a production client deployment with real data, you'd either add Cloudflare Access in front or convert to a Next.js app with proper server-side middleware.

Analytics on plain HTML: the CSP gotcha

Vercel Analytics works on static HTML sites, but the setup has two non-obvious requirements that cost me time.

First, the window.va queue must be declared before the script loads:

head snippet
<script>window.va = window.va || function () { (window.vaq = window.vaq || []).push(arguments); };</script>
<script defer src="/_vercel/insights/script.js"></script>

Second — and this one is subtle — the analytics beacon POSTs to/_vercel/insights/view, which is a same-origin endpoint, not a third-party domain. If your Content Security Policy sets connect-src to only an external domain like https://vitals.vercel-insights.com without 'self', the browser silently blocks every beacon and your dashboard shows zero visitors indefinitely.

vercel.json headers (correct)
"connect-src 'self' https://vitals.vercel-insights.com"

That 'self' is mandatory. Easy to miss, annoying to debug.

Self-hosting on a VPS

Vercel is the fastest path, but some clients won't put analytics data on a third-party CDN. For those cases, the same pipeline — dbt runs, dct render, static HTML — can be served from a VPS (Hetzner Nanosv at €4/month works fine) using a minimal FastAPI auth proxy in front of nginx.

The Docker-based self-host version is in a separate repo: github.com/dirkjbosman/dbt_charts_vps (coming soon)

The architecture is the same. The difference is auth enforcement: on a VPS, the FastAPI middleware checks the session cookie server-side before serving any file. You can't bypass it with DevTools. That's the trade-off for the extra infrastructure.


If you'd prefer a managed version of this — where the pipeline, hosting, and updates are handled for you — I offer that as a service. → Hosted Solutions


Stay in the loop

New articles, tools and experiments — no noise.