Introduction

Predicting SQL query performance before execution helps teams prevent slow queries from degrading application performance, reduce costly database incidents, and guide developers to write efficient SQL. A Workload Analyzer uses historical telemetry and machine learning to estimate execution time, CPU cost, I/O, and likelihood of timeouts or plan regressions for a given SQL query and its parameters.

This article explains how to design and implement a production-ready Workload Analyzer using:

Headers are compact and written in clear technical prose suitable for senior developers.

Goals and scope

Primary goals

Non-goals

High-level architecture

                 ┌─────────────────────┐
                 │ Application / CI    │
                 │ (ASP.NET Core / CI) │
                 └─────────┬───────────┘
                           │ SQL text + params
                           ▼
                 ┌─────────────────────┐
                 │ Workload Analyzer   │
                 │ (API + Model Server)│
                 └──────┬─────┬────────┘
                        │     │
        ┌───────────────▼─┐ ┌─▼────────────────┐
        │ Feature Store   │ │ Model Training   │
        │ (time-series DB)│ │ Pipeline (ML Ops) │
        └────────┬────────┘ └────────┬─────────┘
                 │                   │
        ┌────────▼────────┐  ┌───────▼─────────┐
        │ Telemetry Source│  │ Explainability  │
        │ (DB DMVs, APM)  │  │ & Suggestions   │
        └─────────────────┘  └─────────────────┘

Components

Telemetry collection

Collect rich historical signals to train accurate models:

  1. Execution metrics

    • Duration (ms), CPU time (ms), logical and physical reads, writes, rows returned, plan id, compile time.

  2. Query fingerprint

    • Normalize SQL (remove literals) and compute fingerprint (hash). Useful for grouping.

  3. Query text and plan

    • Store normalized text, query plan XML/JSON (operator tree), index usage.

  4. Runtime context

    • Parameter values (hashed or binned), session settings, transaction isolation, connection pool state.

  5. Server state and load

    • CPU load, memory pressure, concurrent active sessions, buffer cache hit ratio, recent blocking/waits.

  6. Schema metadata

    • Table row counts, index cardinalities, column stats (histograms), last statistics update time.

  7. Temporal context

    • Time of day, day of week, maintenance windows, backup jobs may affect performance.

Sources

Collect telemetry in a time-series store (Prometheus, InfluxDB) or a feature store (Feast, custom DB) for model training.

Feature engineering

Good features matter more than fancy models. Features fall into categories:

Query text features

Plan-based features

Schema / stats features

Parameter features

Server-load features

Temporal features

Derived features

Feature pipelines

Labels (what to predict)

Choose target variables that matter:

You may model multiple targets (multi-output regression/classification) or separate models.

Model choices

Start simple and iterate:

Baseline models

Advanced models

Practical recommendation: start with LightGBM/XGBoost on engineered features; add text embeddings (Sentence-BERT) as numeric features. Move to model ensembles if necessary.

Handling concept drift and data imbalance

Explainability and remediation suggestions

Predictions are most useful when coupled with actionable advice:

Compute SHAP values for GBT models; present top positive contributors and mapped suggestions.

Training pipeline and MLOps

  1. Data ingestion: ETL historical telemetry into training dataset (feature vectors + labels).

  2. Split strategy: time-based split (train on older window, validate on recent window) to prevent leakage.

  3. Cross-validation: time-series aware CV.

  4. Hyperparameter tuning: Optuna or built-in LightGBM tuner.

  5. Model evaluation:

    • Regression: MAE, RMSE, R²; also percentile errors for p90/p99 predictions.

    • Classification: ROC-AUC, precision/recall at operating points.

  6. Model registry: store models with metadata, version, dataset snapshot, and performance metrics (MLflow, Azure ML, or custom).

  7. CI for models: unit tests for feature pipeline, data drift checks, and validation gates before deployment.

  8. Deployment: package model as ONNX or use lightgbm native model served behind .NET API (rest/gRPC). Use containerized model servers and autoscale.

Runtime integration (.NET + Angular)

Prediction API (.NET)

Create service endpoints:

Implementation tips:

Angular UX

Example response payload

{
  "predictedLatencyMs": 1240,
  "predictedP90": 2100,
  "timeoutProb": 0.12,
  "topFactors": [
    {"feature":"seq_scan_orders", "impact":0.34},
    {"feature":"estimated_rows_mismatch", "impact":0.22}
  ],
  "suggestions": ["Create index ON Orders(customer_id)", "Update statistics on Orders"]
}

CI Integration

Feedback loop and human-in-the-loop

Evaluation and acceptance criteria

Run A/B experiments: for a set of queries, apply automated throttling/suggestions to half and compare incident rates.

Operational challenges and mitigations

Dynamic data and plan caching

Plan regressions

Cold-start queries

Scaling the feature store and model server

Testing strategy

Security and privacy

Metrics and monitoring

Expose dashboards in Grafana or Application Insights.

Roadmap and extensions

Summary

A Workload Analyzer that predicts SQL query performance is a high-leverage tool to improve reliability and developer productivity. Key pieces are: