Thursday, November 19, 2026

Smart Grid Balancer on Databricks

 

1. Purpose and scope

This document describes how to move the smart grid balancer from a simulator to a production architecture on the Databricks Data + AI platform. It assumes the source data arrives as streams (wind, solar, hydro, gas, demand, market prices) and lands in a Databricks lakehouse, and that an energy trading portal will be integrated.

It covers:

  • The recommended architecture and why Lakebase is the right operational layer once a trading portal exists
  • The streaming pipeline, data model and balancer deployment
  • How the trading portal connects to the balancer
  • Where the rest of the Databricks ecosystem (Unity Catalog, Lakeflow, Mosaic AI, Genie, Apps) adds value
  • A phased roadmap, risks and open questions.

  • It does not cover market rules, any specific organization’s business logic, regulatory reporting detail or commercial licensing.


2. Executive summary

Recommendation: a hybrid, with Lakebase as the live and transactional layer and the lakehouse as the system of record for history, analytics and ML. A lakehouse-only design is enough while the system is a monitoring dashboard. Balancer Dashboard Demonstrated here is a lakehouse architecture. Once traders place bids and the balancer must act on committed trades, we need ACID transactions, enforced constraints, row-level updates and millisecond point reads for many concurrent users. That is what a managed Postgres (Lakebase) provides.

•        Streaming ingestion uses Zerobus Ingest (direct, no message bus) or Kafka where it already exists, feeding Lakeflow Spark Declarative Pipelines in a bronze, silver, gold layout.

•         The balancer becomes a stateful, idempotent service. Store levels, configuration and every dispatch decision live in Lakebase and are written in one transaction per tick, so restart and replays are safe.

•     The trading portal reads the balancer’s surplus and deficit outlook, writes orders and trades to Lakebase, and its committed trades feed back into the balancer as export, import and flexible-load sinks. This also gives the balancer a real answer to curtailment when every store is full.

•     AI is added in stages forecasting models for wind, solar, demand and price; a forecast-driven optimizer to replace the current heuristic; and agents and Genie for operators and traders. Genie Ontology translates raw data into a business-aware map of the organization which increased AI accuracy on business questions from roughly 50% to over 80%.

 3. Lakehouse-only or Lakebase

 3.1 What each is good at

The lakehouse (Delta tables in Unity Catalog, queried with Spark or a SQL warehouse) is built for large scans, history, feature engineering and model training. Lakebase is managed, serverless Postgres that shares OLTP storage foundations with the lakehouse and is aimed at applications, agents and operational workloads.

Criterion

Lakehouse only

Lakebase plus lakehouse

Main strength

Analytics over history, ML training, BI

Transactional state, app backends, low-latency point reads

Write pattern

Appends and micro-batches; row updates via MERGE

Single-row INSERT and UPDATE with ACID transactions

Order book and trades

Awkward: constraints are informational, no row locks

Natural: primary keys, unique idempotency keys, foreign keys, row locks

Many concurrent portal users

Each small query goes through a warehouse

Standard connection pooling and indexed queries

Live balancer state

Possible but heavy for frequent small updates

Fits: a few rows updated every tick

Governance

Unity Catalog

Same Unity Catalog umbrella

Tooling

Spark, SQL, notebooks

Standard Postgres drivers, PostgREST, pgvector, PostGIS and other extensions

Dev and test safety

Table clones

Instant branches and point-in-time recovery

3.2 Decision rule

•    No trading portal, monitoring only As attached herewith: lakehouse-only is sufficient. We serve the dashboard from a SQL warehouse or an AI/BI dashboard.

•    Trading portal, order handling or any write-back from users: we use Lakebase for the live layer. Orders, positions, limits, configuration and balancer state need transactions and constraints.

•     Always: we keep the lakehouse for history, KPIs, ML and cross-domain analytics. The two are complementary, not alternatives.

3.3 Product status to verify before committing

As of this writing, Lakebase is generally available on AWS and on Azure (Azure GA was announced on 3 March 2026), supports Postgres 17, and is governed through Unity Catalog. Synced tables, which copy Unity Catalog tables (Delta, Iceberg, views and materialized views) into Lakebase Postgres, are generally available. LTAP Direct Writes, an accelerated sync option, is in Beta. Real-Time Mode for Spark Declarative Pipelines is in Public Preview, and Zerobus Ingest is generally available with a Kafka-compatible API in Beta. We confirm cloud, region and feature status for our workspace before design sign-off.

4. Target architecture

target architecture · lakehouse, balancer, Lakebase, portal and AI

target architecture · lakehouse, balancer, Lakebase, portal and AI

The lakehouse feeds the balancer, the balancer writes live state to Lakebase, and the portal and AI services sit on top, all under one governance layer.

The end-to-end flow:

1.  Telemetry and market feeds land in bronze tables through Zerobus Ingest, Kafka or Lakeflow Connect.

2. Pipelines validate the data and align it to 15-minute ticks (silver).

3. Each tick, the balancer reads the silver inputs, forecasts, live settings and committed trades. It decides how to serve demand, use stores and gas, and handle surplus, then records the result in Lakebase in one transaction.

4. The portal and operator UI read live state and the outlook from Lakebase, and traders’ orders and executed trades are written back to it.

5. Committed trades become inputs to later ticks, and decisions, orders and trades also flow to the lakehouse for history and analytics.

6. Models train on that history and publish forecasts, which synced tables serve back to Lakebase.

4.1 Layers

Layer

Technology

Role

Ingestion

Zerobus Ingest, Kafka, Lakeflow Connect

Land every stream in Delta with Unity Catalog governance

Transformation

Lakeflow Spark Declarative Pipelines

Bronze to silver to gold, data-quality expectations, CDC

Orchestration

Lakeflow Jobs

Schedules, retries, dependencies, repair and rerun

Live state and transactions

Lakebase

Balancer state, config, orders, trades, positions, audit

History and ML

Delta Lake, MLflow, Model Serving

Training data, models, backtests

Applications

Databricks Apps

Dashboard, trading portal, operator tools

Governance

Unity Catalog

Access control, lineage, audit across lakehouse and Lakebase

Intelligence

Mosaic AI, Genie, AI/BI

Forecasts, optimiser, agents, natural-language analytics

4.2 Two-way data flow between Lakebase and the lakehouse

• Delta to Lakebase: synced tables serve analytics-grade data (forecasts, price curves, KPI aggregates, ML features) to the portal with low latency. In Postgres the Unity Catalog schema name becomes the Postgres schema name.

• Lakebase to Delta: orders, trades, dispatch decisions and configuration changes must reach the lakehouse for analytics and ML. Changes are synchronized from Lakebase into Unity Catalog governed Delta tables using native Lakebase replication and change-data-capture capabilities. This provides a consistent operational data foundation for analytics, reporting, AI, and machine learning workloads without introducing separate event-publication mechanisms or dual-write dependencies, avoid outbox pattern: write an outbox row in the same transaction, and a small relay publishes it through Zerobus Ingest into Delta. This avoids unsafe dual writes.

5. Streaming pipeline design

5.1 Streams and ingestion

Stream

Typical source

Ingestion

Notes

Wind and solar available power

Farm SCADA, inverters, weather forecasts

Zerobus Ingest or Kafka

Capture measured and forecast values separately

Demand

Smart meters, grid operator feed

Kafka or Lakeflow Connect

Aggregate to feeder or region

Hydro inflow and reservoir level

Hydrology sensors

Zerobus Ingest

Inflow is an input; the reservoir level is balancer state

Gas pipeline resupply and fuel-store level

Pipeline operator

Zerobus Ingest or file or API connector

Resupply is an input

Market prices and trades

Exchange, broker or ISO feed

Kafka or API connector

Replaces the demand-based price formula

Every event carries its event time, ingest time, source, and a unique identifier, enabling event-time processing, deduplication, and replay without double counting. Watermarking is applied to handle late-arriving data within a configurable time threshold while ensuring accurate aggregations and state management.

5.2 Medallion layout

• Bronze: raw append-only events, schema-on-read where sources are unreliable.

• Silver: validated, deduplicated and aligned to 15-minute ticks. Quality expectations drop or quarantine bad rows, for example negative demand, wind above installed capacity, or timestamps far in the future. Late data is handled with a watermark, and a correction path reprocesses closed ticks.

• Gold: tick-level grid_inputs (one row per tick with demand, wind, solar, hydro inflow and gas resupply), cumulative KPIs, baseline comparisons and daily summaries as materialized views.

5.3 Latency

The balancer’s decision interval is 15 simulated minutes, so a typical operational budget is seconds from sensor to silver, not milliseconds. Standard streaming with Zerobus Ingest is sufficient for balancing. Real-Time Mode (millisecond-scale) is worth evaluating later for price-triggered trading alerts and fast frequency-response use cases, not for the 15-minute dispatch itself.

6. Balancer service

6.1 Deployment options

Option

When to use

Trade-offs

Continuous Lakeflow Job running the Python balancer, reading silver and writing to Lakebase

Default

Simple operations, managed retries, Unity Catalog identity

Databricks App with a background worker

If the balancer and portal share one deployable

Couples the lifecycles of dispatch and UI

Stateful Structured Streaming operator

If the balancer must scale across many regions or assets

More engineering effort; state must still be persisted

We start with the first option and keep the dispatch logic separate from state handling (inputs and state in, decisions and new state out), so it can be tested and replayed.

6.2 Exactly-once tick processing

Each tick is processed in one Postgres transaction. A crash before commit leaves the state unchanged, and a replay of the same tick is a no-op.

1.   Lock the current store state for the run.

2. Read the live settings and the committed trade schedule for the interval.

3. Run the dispatch logic on the interval’s inputs.

4. Record the decision, ignoring it if that tick was already recorded.

5. Update store levels and queue an event for the lakehouse (outbox).

6. Commit, then notify listeners such as the portal and dashboard.

6.3 Configuration

Operating settings, such as the cost-versus-CO₂ priority, the reserve level and storage limits, live in a configuration table in Lakebase instead of process memory. The portal or dashboard edits them, every change is audited, and the balancer reads them at the start of each tick. Branching lets us test a configuration change against a copy of production data before applying it.

6.4 Baseline

The no-storage baseline stays a stateless calculation in the same tick, from the same inputs, stored beside the actual result. We document its assumptions in the data catalog. In particular, the prototype’s baseline gas has no ramp or fuel limit, so the optimiser can look worse on cost when it hits those limits. We also consider adding a second, constrained baseline for a fairer comparison.

7. Data model

7.1 Lakebase (operational)

Entity

Purpose

Key attributes

Written by

Run

One balancing run or scenario

Run id, start time, scenario settings

Balancer

Configuration

Live operating settings

Setting, value, who changed it and when

Portal, dashboard

Store state

Current level of each store (wind battery, solar battery, hydro reservoir, gas fuel store)

Level, capacity, last gas output

Balancer

Dispatch decision

The result for each 15-minute tick

Demand, output by source, charging, curtailment, unserved demand, price, reserve, note

Balancer

Order**

Buy and sell orders per delivery interval

Order id, idempotency key, desk, side, interval, MW, limit price, status

Portal, strategies

Trade**

Executed trades linked to orders

Trade id, order, counterparty, MW, price, interval

Trading engine

Committed schedule

Net export or import per interval, derived from trades

Interval, net MW

Derived view, read by the balancer

Audit and outbox

Change history and events waiting to reach the lakehouse

Actor, action, payload

All writers

Primary keys, unique idempotency keys and foreign keys keep orders and trades consistent, and the committed schedule gives the balancer one place to read trading commitments.

7.2 Lakehouse (analytical)

Layer

Tables

Bronze

raw_wind, raw_solar, raw_demand, raw_hydro, raw_gas, raw_market_prices

Silver

grid_inputs_15min, quality_quarantine, forecast_actuals

Gold

dispatch_history, kpi_daily (CO₂, cost, unserved, curtailed against baseline), store_levels_15min, trade_history, ml_features

8. Trading portal integration **

8.1 Why this is the deciding factor for Lakebase

A trading portal is an operational application: users submit orders, modify them, cancel them and see positions in real time. It needs unique idempotency keys so a double-click does not create two orders, transactions that move an order, trade and position together, row-level locking for matching queues, and fast reads for many users. Those are Postgres strengths and awkward on append-oriented analytical tables.

8.2 Interaction with the balancer

1. Outlook to portal. The balancer, using forecasts, publishes expected surplus or deficit per upcoming interval (for example the next 24 hours) to a Lakebase table the portal reads.

2. Orders from the portal. Traders place sell orders for expected surplus and buy orders for expected deficit, or an automated strategy does so within limits.

3. Committed trades to the balancer. Executed trades become a fixed schedule: committed exports raise effective demand, committed imports lower it. The balancer treats them as inputs for that interval.

4. Surplus sink. Exports and contracted flexible loads become additional places for surplus beyond batteries and pumped hydro, reducing curtailment. In cross-charging and pumped hydro section, removes avoidable curtailment, and removes more of what remains by trading.

5. Price. The market price feed replaces the demand-based formula, so cost and dispatch priority reflect real prices.

6. Risk limits. Maximum position, maximum export per interval and per-desk limits are enforced by database constraints and checked by the balancer before it relies on a trade.

8.3 Portal technology

• Databricks Apps: for a portal built on the platform, with workspace identity and on-behalf-of-user access so Unity Catalog permissions apply. A web framework such as FastAPI or React with a Postgres driver connects to Lakebase.

•  External portal: connect over the Postgres wire protocol using OAuth tokens and private networking; the standard drivers and tools (pgAdmin, DBeaver, PostgREST) work.

• Live updates: replace SSE with Postgres LISTEN/NOTIFY into a WebSocket gateway, or poll indexed queries.

8.4 Access control and audit

We use Unity Catalog roles for desks and operators, with row-level or attribute-based filters so a trader sees only their desk’s orders. Every order and configuration change goes into an append-only audit table. We confirm which market-transparency and reporting rules apply in our jurisdiction (for example REMIT in the EU) and design the audit trail to support them.

9. Using the wider Databricks Data + AI platform

Capability Use in this system

Unity Catalog

One governance model across Delta and Lakebase: access control, lineage from sensor to dispatch to trade, audit, data classification

Lakeflow Connect and Zerobus Ingest

Telemetry and market ingestion without running a message bus where a direct path suffices

Spark Declarative Pipelines

Medallion pipelines with data-quality expectations, CDC and automatic incremental processing

Lakeflow Jobs

Orchestrate the balancer, model retraining and backtests with retries and alerts

MLflow and Model Serving

Track, register (in Unity Catalog) and serve forecasting models behind an endpoint

Feature serving

Offline features in Delta, online features in Lakebase for low-latency inference

Mosaic AI and agents

Operator and trader copilots that call tools (simulator, dispatch history, orders) with governed access

AI/BI Genie

Natural-language questions on gold tables: “Why did curtailment rise on Tuesday?”

AI/BI dashboards

KPI views for CO₂, cost, unserved demand and curtailment against baseline

Databricks Apps

Host the dashboard and trading portal next to the data

pgvector in Lakebase

Retrieval over runbooks, market notices and past incident reports for agents

Delta Sharing

Share datasets with grid operators, regulators or partners without copying

Branching and point-in-time recovery (Lakebase)

Test configs and migrations on production-like data and recover from errors

Asset Bundles and CI/CD

Version and deploy pipelines, jobs, apps and schemas as code

Lakehouse Monitoring

Detect data and model drift on forecasts and inputs

9.1 Forecasting

We train models for wind, solar, demand and price on silver history, with weather forecasts as features. We register them in Unity Catalog, serve them, and write predictions back as Delta tables, which synced tables expose to the portal and balancer. We track forecast error by horizon so the optimiser can weigh uncertainty.

9.2 From heuristic to optimiser

Today the balancer follows a rule: stores serve only when demand exceeds a trailing average scaled by the priority setting. With forecasts, we replace it with a rolling-horizon optimiser (model predictive control) that plans store charging and discharging, gas ramping and trade volumes over the next 24 hours and applies only the first step. We keep the existing rule-based logic as the fallback and as the reference the optimiser is judged against, using MLflow to compare runs.

9.3 Simulator and digital twin

We keep the prototype’s synthetic data generators and dispatch logic as a simulator. We use it to backtest policies on historical and synthetic scenarios (low-wind weeks, gas supply disruption, price spikes), to generate training data, and as a what-if tool for agents.

9.4 Agents

An operator agent can explain a decision (“Why is it holding stores for the peak?”), run a what-if on the simulator, and draft a configuration change for human approval. A trader agent can summarize the position and propose orders within limits. All actions go through governed tools and an approval step, and are logged to the audit table.

10. Non-functional requirements

• Availability and recovery: use Lakebase’s point-in-time recovery and a documented recovery procedure for the balancer; tick replay makes recovery safe.

• Compute settings: scale-to-zero suits development, but a live trading and balancing workload needs a minimum capacity so it is never cold.

•  Security: private networking, firewall and NSG rules, managed identities or OAuth for all connections, secrets in a centralized secret store, least-privilege service permissions, and Unity Catalog RBAC/ABAC governance.

• Observability: metrics for ingestion lag, tick processing time, decision latency, unserved MW and sync lag between Delta and Lakebase, with alerts.

• Data quality: expectations in silver, quarantine tables, and a daily reconciliation between Lakebase dispatch_tick and Delta dispatch_history.

• Testing: unit tests on balance(), scenario replays, and branch-based rehearsals for schema or config changes.

• Cost: per-second pricing for ingestion and serverless compute; review Lakebase capacity, retention and sync schedules regularly.

11. Risks and open questions

• Feature status: confirm Lakebase availability for our cloud and region, the current mechanism and status for Lakebase-to-lakehouse sync, LTAP Direct Writes (Beta), Kafka-compatible Zerobus (Beta) and Real-Time Mode for pipelines (Public Preview).

• Dual-write consistency: monitor Lakebase-to-Delta replication health, CDC lag, and synchronization failures.

• Baseline fairness: the current baseline lacks ramp and fuel limits; agree on the definition before presenting savings to stakeholders.

• Model risk: forecast errors propagate into dispatch and orders; define fallbacks and human approval thresholds.

• Market and regulatory rules: reporting, position limits and settlement timing vary by market and must be confirmed with the trading and compliance teams.

• Data ownership and SLAs: agree owners, update frequencies and latency targets for each source feed.

• Capacity planning: estimate asset counts, tick frequency and retention to size Lakebase and the pipelines.

12. References

• Databricks documentation: Serve lakehouse data with synced tables (Lakebase)
• Databricks blog: Azure Databricks Lakebase is generally available (3 March 2026)
• Databricks blog: Lakeflow and the new era of agentic data engineering (Zerobus Ingest, Spark                Declarative Pipelines Real-Time Mode) Databricks product page: Zerobus Ingest