a month ago
When teams start looking at Databricks cost, the first instinct is usually to query system.billing.usage.
That gives a good view of Databricks consumption, but it is only one part of the overall cost picture..
For a more complete FinOps view on Azure, I wanted to answer questions such as:
The solution ended up combining four different data sources
Azure Cost Management Exports
+
Databricks Billing System Tables
+
Azure Blob Inventory
+
Azure Monitor Storage Metrics
|
v
FinOps Attribution Layer
|
v
Team / Product / Application ChargebackThis post walks through in detail on how I implemented that pattern.
1. Solution Architecture and Attribution Flow
At a high level, the architecture looks like this:
NonProd Azure Subscription
┌────────────────────────────┐
│ Cost Management Exports │
│ - FOCUS │
│ - Actual Cost │
│ - Amortized Cost │
│ │
│ Storage Accounts │
│ - Blob Inventory │
└──────────┬─────────────────┘
│
│
▼
┌────────────────────────────┐
│ Central Prod Storage │
│ │
│ staging/ │
│ focus/ │
│ actual/ │
│ amortized/ │
│ │
│ blob_inventory/ │
└──────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ Databricks / Unity Catalog │
│ │
│ azure_exports volume │
│ blob_inventory volume │
│ │
│ system.billing.usage │
│ system.billing.list_prices │
│ system.lakeflow.* │
└───────────┬──────────────────┘
│
▼
┌────────────────────────────┐
│ FinOps attribution tables │
│ │
│ workspace │
│ job │
│ cluster │
│ storage account │
│ catalog/schema/volume │
│ application/team │
└────────────────────────────┘The reference architecture above shows how the data is collected and landed. The next view focuses on how those data sources are translated into workload, storage, ownership, and chargeback attribution.
finops_flow
2. Getting Azure Cost Data into Databricks
Azure cost Management exports are useful because they give us Azure-side costs independently of the Databricks billing tables.
I have used three datasets:
- Actual Cost
- Amortized Cost
- FOCUS Cost
FOCUS is particularly interesting if you want to build a cloud-agnostic FinOps model later.
Azure currently supports ActualCost, AmortizedCost and FocusCost export types, together with CSV or Parquet output. Reference
Also, I preferred
Format : Parquet
Compression : Snappy
Partitioning : Enabled
Frequency : Daily
Timeframe : MonthToDateAzure's export API supports Parquet, Snappy compression, file partitioning and configurable overwrite behaviour.
3. Automating Azure Cost Management Exports
The export can be configured directly from a Databricks notebook.
Authentication can use a service principal:
from azure.identity import ClientSecretCredential
credential = ClientSecretCredential(
tenant_id=TENANT_ID,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET
)
token = credential.get_token(
"https://management.azure.com/.default"
).tokenThen construct the export:
import requests
from datetime import datetime, timezone, timedelta
scope = f"/subscriptions/{SOURCE_SUBSCRIPTION_ID}"
url = (
"https://management.azure.com"
f"{scope}/providers/Microsoft.CostManagement/"
f"exports/{EXPORT_NAME}"
"?api-version=2025-03-01"
)
start = (
datetime.now(timezone.utc) + timedelta(minutes=5)
).strftime("%Y-%m-%dT%H:%M:%SZ")
payload = {
"location": "global",
"identity": {
"type": "SystemAssigned"
},
"properties": {
"schedule": {
"status": "Active",
"recurrence": "Daily",
"recurrencePeriod": {
"from": start,
"to": "2027-12-31T23:59:59Z"
}
},
"format": "Parquet",
"compressionMode": "snappy",
"partitionData": True,
"dataOverwriteBehavior": "CreateNewReport",
"deliveryInfo": {
"destination": {
"resourceId": DESTINATION_STORAGE_ACCOUNT_ID,
"container": "staging",
"rootFolderPath": "amortized"
}
},
"definition": {
"type": "AmortizedCost",
"timeframe": "MonthToDate",
"dataSet": {
"granularity": "Daily"
}
}
}
}
r = requests.put(
url,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
},
json=payload
)
r.raise_for_status()The current Cost Management REST API documents this create/update pattern and the available export properties.
For Configuring FOCUS cost, follow the same above by just replacing the definition as:
"definition": {
"type": "FocusCost",
"timeframe": "MonthToDate",
"dataSet": {
"granularity": "Daily"
}
}4. Centralising Cost Exports Across Subscriptions
One useful pattern is:
NonProd Subscription ──┐
├──> Prod Storage Account
Prod Subscription ─────┘The export scope does not need to be the same subscription as the destination storage account.
For example:
scope = "/subscriptions/<NONPROD_SUBSCRIPTION>"while:
DESTINATION_STORAGE_ACCOUNT_ID = (
"/subscriptions/<PROD_SUBSCRIPTION>"
"/resourceGroups/<rg>"
"/providers/Microsoft.Storage/storageAccounts/<account>"
)This allows all Azure cost exports to land centrally.
There are two identities to think about:
Automation Service Principal
|
| creates/manages export
v
Azure Cost Management Export
|
| system-assigned managed identity
v
Destination Storage AccountIn my setup the permissions were roughly:
Automation SPN
Cost Management Contributor
on source subscription
Export Managed Identity
Storage Blob Data Contributor
on destination storageThis distinction matters. The identity creating the export is not necessarily the identity writing the exported files.
5. Understanding MonthToDate Export Behaviour
This caught me out initially.
I expected a daily MonthToDate export for a date like August 3 to simply contain: August 1 -> August 3.
And it does.
But during the first few days of August, Azure can also regenerate: July 1 -> July 31.
So storage might look like:
20260701-20260731/
202608010207/
202608020530/
202608030531/
20260801-20260831/
202608010210/
202608020533/
202608030535/The important distinction is:
20260701-20260731
^
|
Cost period
202608030531
^
|
Export run timestampAzure deliberately reruns the prior month during the first five days of the new month because late usage and charges can arrive after month end. Microsoft documents that daily exports may run for both the current month and previous month during this period.
That matters enormously for downstream ingestion. If every file is blindly appended into a Delta table, July gets duplicated multiple times. So, be cautious there in handling the latest snapshot.
6. Choosing the Right Export Overwrite Strategy
There are two useful modes:
OverwritePreviousReport
CreateNewReportAzure documents CreateNewReport as the default and allows OverwritePreviousReport to replace the report for the same month.
For raw FinOps data, I prefer:
"dataOverwriteBehavior": "CreateNewReport"Because immutable raw files work much better with file-arrival processing and auditability.
I would rather retain:
period
run1
run2
run3and decide in the Silver layer which run is authoritative.
For example:
runs = [
x for x in dbutils.fs.ls(period_path)
if x.isDir()
]
latest = max(
runs,
key=lambda x: x.name.rstrip("/")
)
latest_path = latest.pathThe Bronze layer can remain immutable while Silver reconciles or replaces the affected month.
7. Making Azure Cost Exports Available through Unity Catalog
I would avoid pointing an external Azure service directly into a Databricks-managed internal location such as:
_unitystorage/...Instead, create a clean external landing area:
abfss://staging@finopsstorage.dfs.core.windows.net/azure_exports/and register it through an external location / external volume.
CREATE EXTERNAL VOLUME prod_staging.finops.azure_exports
LOCATION
'abfss://staging@finopsstorage.dfs.core.windows.net/azure_exports';The result is a predictable Databricks path:
/Volumes/prod_staging/finops/azure_exports/The exports then be organised as:
azure_exports/
focus/
actual/
amortized/8. Ingesting Cost Exports into Delta
The raw export can be consumed directly via Auto Loader based File Arrival Trigger:
df = (
spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "parquet")
.load(
"/Volumes/prod_staging/"
"finops/azure_exports/amortized/"
)
)But remember: file ingestion and cost snapshot semantics are different things.
Every MonthToDate export overlaps the previous one.
So I treat the layers differently:
Raw / Bronze
append every export file
Silver
reconcile by billing period / charge date
Gold
aggregate once per resource/team/product9. Attributing Databricks Platform Cost
It contains usage quantities, product information, job/cluster metadata, identity metadata and custom tags.
To calculate list-price cost, join as
SELECT
u.workspace_id,
u.usage_metadata.job_id,
u.sku_name,
SUM(
u.usage_quantity *
p.pricing.effective_list.default
) AS list_cost
FROM system.billing.usage u
JOIN system.billing.list_prices p
ON u.cloud = p.cloud
AND u.sku_name = p.sku_name
AND u.usage_end_time >= p.price_start_time
AND (
p.price_end_time IS NULL
OR u.usage_end_time < p.price_end_time
)
WHERE u.billing_origin_product = 'JOBS'
GROUP BY ALLThis same usage-to-price joining pattern has been documented as well for cost analysis.
10. Attributing Jobs Compute to Workloads
Jobs Compute is particularly nice for attribution because billing usage can contain:
usage_metadata.job_id
usage_metadata.job_run_id
usage_metadata.cluster_idFor Jobs Compute and serverless Jobs, job_id is populated in billing usage.
We can enrich that with:
system.lakeflow.jobs
system.lakeflow.job_run_timelineDatabricks provides dedicated examples for joining job billing usage with Lakeflow job metadata and run timelines.
11. Bringing Azure VM Cost into the Picture
This is an important distinction.
For classic Jobs Compute:
Databricks Job Cost
=
Databricks DBU cost
+
Azure VM / infrastructure costsystem.billing.usage gives us the Databricks side.
Azure Cost Management gives us the infrastructure side.
Fortunately, Databricks applies Azure resource tags such as:
Vendor
ClusterId
ClusterName
Creatorto classic Jobs and all-purpose compute. Those tags propagate into Azure cost reporting.
That gives us the bridge:
Databricks
system.billing.usage
|
| cluster_id
v
Azure Cost Export
|
| ClusterId tag
v
Azure VM / infrastructure costConceptually:
SELECT
d.job_id,
d.cluster_id,
SUM(d.databricks_cost) AS databricks_cost,
SUM(a.azure_vm_cost) AS azure_vm_cost,
SUM(d.databricks_cost) + SUM(a.azure_vm_cost) AS total_job_cost
FROM databricks_usage d
LEFT JOIN azure_cost a
ON d.cluster_id = a.cluster_id
GROUP BY ALLThat starts giving us something much closer to the real cost of a workload.
12. Storage is harder than compute
Compute naturally has IDs:
job_id
cluster_id
warehouse_idStorage is less straightforward.
Azure Monitor can answer: How large is this storage account?
but it cannot automatically answer: How many bytes belong to catalog_a.schema_b.volume_c?
That requires another layer.
13. Measuring Storage Account Footprint with Azure Monitor
Azure exposes the account-level UsedCapacity metric.
Eg:
def get_used_capacity(storage_id, date_str):
url = (
f"https://management.azure.com{storage_id}"
"/providers/Microsoft.Insights/metrics"
)
params = {
"api-version": "2018-01-01",
"metricnames": "UsedCapacity",
"aggregation": "Average",
"timespan": (
f"{date_str}T00:00:00Z/"
f"{date_str}T23:59:59Z"
),
"interval": "PT1H"
}
r = requests.get(
url,
headers={"Authorization": f"Bearer {token}"},
params=params
)
r.raise_for_status()
points = (
r.json()["value"][0]
["timeseries"][0]["data"]
)
points = [
p for p in points
if p.get("average") is not None
]
return points[-1]["average"]Azure documents UsedCapacity as an account-level storage capacity metric.
That solves:
Storage Account A = 11.2 TiB
Storage Account B = 7.4 TiBBut it doesn't not solve
catalog1.schema1.volume1 = ?14. Going Beyond Account-Level Storage with Blob Inventory
For more granular attribution, Azure Blob Inventory is very useful.
It can produce scheduled inventories containing fields such as:
Container
Name
Content-Length
BlobType
Creation-Time
Last-Modifiedand supports Parquet output. Reference.
A daily inventory produces like:
staging/
2026/
07/
01/
23-14-09/
storage_inventory/
manifest.json
inventory_0.parquetThat hierarchy is Azure-generated.
For each relevant storage account, I configured:
Blob Inventory
Object type : Blob
Format : Parquet
Frequency : Daily
Content-Length : included
Name : included
Container : includedBlob Inventory writes to a storage container rather than directly to a UC volume. I therefore land each storage account’s inventory in its configured container and use a Databricks maintenance job to consolidate the latest Parquet snapshots into a UC-backed blob_inventory volume.
/Volumes/prod_staging/
finops/
blob_inventory/15. Why Blob Inventory Works Better than Recursive Volume Scans
You can calculate a volume size with:
def size(path):
total = 0
for item in dbutils.fs.ls(path):
if item.isDir():
total += size(item.path)
else:
total += item.size
return totalIt works. But for large volumes, it gets expensive and slow.
In one test, recursively traversing a roughly 1.4 TiB volume took several minutes. Parallelising directory listing reduced it significantly, but it still means repeatedly enumerating storage.
Blob Inventory moves that work to Azure and produces a dataset we can query efficiently.
16. Mapping Storage Bytes Back to Unity Catalog
Blob Inventory tells us what physically exists in the storage account:
container, blob_path, content_lengthBut chargeback needs a logical view:
catalog
schema
table/volume
team
cost_centerSo the next step is resolving storage paths back to Unity Catalog objects.
For external volumes and predictable paths, this can be straightforward. Unity Catalog metadata can be obtained from information schema tables such as:
system.information_schema.volumes
system.information_schema.tables
system.information_schema.schemataThe mapping layer then looks roughly like:
storage_account
container
path_prefix
catalog
schema
object_type
object_name
team
cost_centerBlob Inventory can then be aggregated against that mapping:
SELECT m.catalog_name,
m.schema_name,
m.object_type,
m.object_name,
m.team,
SUM(i.content_length) AS bytes
FROM finops.blob_inventory i
JOIN finops.storage_uc_mapping m
ON i.storage_account = m.storage_account
AND i.container = m.container
AND i.blob_name LIKE CONCAT(m.path_prefix, '%')
GROUP BY ALLThis gets us from:
Storage Account = 25 TiBto something much more useful:
Finance
finance_prod.raw 5.3 TiB
landing volume 1.5 TiB
transactions table 2.8 TiB
reference table 1.0 TiBManaged UC storage needs one extra step
Managed Unity Catalog objects do not always expose friendly paths. Blob Inventory may contain paths such as:
/catalogs/<uuid>/
/tables/<uuid>/
/volumes/<uuid>/In that case the UUID in the physical path needs to be resolved back to UC metadata.
A practical resolution chain is:
Blob path
↓
Extract catalog/table/volume UUID
↓
Unity Catalog metadata
↓
catalog + schema + table/volume
↓
team / cost centerA periodically refreshed UUID inventory also preserves mappings for objects that may later be dropped and disappear from current information-schema metadata. This table has below schema.
object_uuid
object_type
catalog_name
schema_name
object_nameThis is especially useful for managed tables and volumes where the physical ADLS path is intentionally abstracted by Unity Catalog.
The important point is that Blob Inventory measures bytes, UC metadata resolves ownership.
17. Allocating Storage Cost to Catalogs, Schemas and Teams
Once storage bytes have been resolved to catalogs and schemas, the Azure storage cost can be allocated proportionally.
There are two measurements involved:
account_total_bytes
-> Azure Monitor UsedCapacity
schema_bytes
-> Blob Inventory + UC resolutionUsedCapacity is the denominator while Blob Inventory provides the ownership numerator.
The allocation is:
schema_share =
schema_bytes / account_total_bytes
schema_storage_cost =
storage_account_cost × schema_shareFor example:
Storage account cost = £4,000
Total attributed size = 20 TiB
Finance schema = 5 TiBThen:
Finance share = 5 / 20 = 25%
Finance storage cost
= £4,000 × 25%
= £1,000The same logic can roll up or down:
Storage Account
↓
Catalog
↓
Schema
↓
Table / Volume
↓
Team / Cost CenterA simplified SQL version:
SELECT
team,
schema_name,
schema_bytes,
account_total_bytes,
schema_bytes / account_total_bytes AS storage_share,
storage_account_cost *
(schema_bytes / account_total_bytes)
AS allocated_storage_cost
FROM finops.storage_attribution;Keep residual storage visible
Not every byte in a storage account will necessarily map to a Unity Catalog object.
For example:
checkpoints
logs
temporary files
non-UC data
unresolved pathsSo:
Storage account cost
|
+--> UC-attributed cost
|
+--> Residual / non-UC costThat residual should not silently disappear or be forced onto mapped schemas.
It can either remain as platform/shared cost or be allocated using an agreed rule.
A useful reconciliation check is:
UC-attributed cost + Residual cost = Storage account cost18. Direct Attribution vs Shared-Cost Allocation
Not every cloud cost should be treated in the same way.
Some costs have a strong technical owner and can be attributed directly.
Directly Attributable: These can often be mapped directly.
Databricks Job DBUs
Job VM cost
Managed Disk cost for that compute
Dedicated SQL warehouse
Dedicated storage path / volumeThese can often be linked directly through:
job_id
cluster_id
warehouse_id
resource tags
storage path
UC object ownershipShared / allocated: Other costs are shared by multiple workloads:
Shared storage accounts
Shared clusters
Network cost
Private endpoints
Monitoring
Platform services
Shared subscription resourcesThese need allocation rules, like:
Storage
allocate by bytes
Network
allocate by traffic if available
otherwise by workload ratio
Shared platform compute
allocate by DBUs or runtime
Shared subscription services
allocate by agreed business ruleA chargeback system should preserve that distinction.
Note: Managed Disk costs follow the VM/compute attribution path and are deliberately excluded from Blob/UC storage allocation.
19. Using Tags for Ownership and Chargeback
For compute, I recommend enforcing tags these tags through Databricks Asset Bundles or your standard deployment process:
team = finance
application = risk-platform
environment = prod
cost_center = CC1234
product = market-dataDatabricks propagates custom tags into system.billing.usage, making them directly usable for cost attribution. Databricks specifically recommends tags for chargeback and showback use cases.
SELECT
custom_tags['team'] AS team,
SUM(
usage_quantity *
p.pricing.effective_list.default
) AS databricks_cost
FROM system.billing.usage u
JOIN system.billing.list_prices p
ON u.cloud = p.cloud
AND u.sku_name = p.sku_name
AND u.usage_end_time >= p.price_start_time
AND (
p.price_end_time IS NULL
OR u.usage_end_time < p.price_end_time
)
GROUP BY custom_tags['team'];That is much cleaner than trying to infer ownership after the workload has run.
20. Building the Ownership Mapping Layer
Eventually I found it useful to maintain a small organisational mapping table.
CREATE TABLE finops.resource_ownership (
resource_type STRING,
resource_id STRING,
workspace_id STRING,
team STRING,
application STRING,
product STRING,
cost_center STRING,
environment STRING,
valid_from DATE,
valid_to DATE
)This mapping layer acts as the business ownership bridge between technical Databricks/Azure identifiers and the reporting dimensions used for showback and chargeback.
21. Building the Unified FinOps Cost Model
At this point we have several facts:
Azure cost export
Databricks usage
Blob inventory
Storage metrics
Ownership metadataThe idea is to create a dedicated/ Unified Gold model such as: finops.team_cost_daily combining the above and having schema like:
date
team
application
environment
databricks_compute_cost
azure_vm_cost
storage_cost
network_cost
other_azure_cost
direct_cost
allocated_cost
total_costThen, summarize the cost as:
SELECT
date,
team,
SUM(databricks_compute_cost) AS databricks,
SUM(azure_vm_cost) AS vm,
SUM(storage_cost) AS storage,
SUM(network_cost) AS network,
SUM(total_cost) AS total
FROM finops.team_cost_daily
GROUP BY date, team22. Start with Showback Before Chargeback
One lesson I would strongly recommend: start with showback.
Before actually charging teams, first publish the model and let teams validate it. Because, questions would arise like: Why is this job mine? Why did storage double? Why is this shared cluster allocated to us? Why does Azure show more than Databricks?
Chargeback only works when people trust the attribution logic.
23. Reconciling Azure and Databricks Costs
It is tempting to expect:
Azure bill = system.billing.usageThey should not be expected to match one-to-one because they represent different layers of consumption. Think of two sources as:
Databricks system.billing
-> Databricks billable platform consumption
Azure Cost Management
-> Azure infrastructure and cloud service consumptionFor classic compute, the real workload cost is closer to:
DBU cost + Azure VM cost + storage + network + shared platform allocationFor serverless, the model changes because infrastructure is packaged differently into the Databricks service.
24. Putting the FinOps Pipeline into Operation
The final process looks roughly like this:
Daily
│
├── Azure Cost Exports
│ ├── Actual
│ ├── Amortized
│ └── FOCUS
│
├── Azure Blob Inventory
│ └── per storage account
│
├── Azure Monitor
│ └── UsedCapacity
│
├── Databricks System Tables
│ ├── billing.usage
│ ├── billing.list_prices
│ ├── lakeflow.jobs
│ └── lakeflow.job_run_timeline
│
└── FinOps ETL
│
├── reconcile cost snapshots
├── map cluster -> Azure cost
├── map blob -> UC volume
├── map technical resource -> team
│
▼
Team Cost Mart
│
├── dashboards
├── budgets
├── alerts
├── showback
└── chargeback25. Practical Lessons and Gotchas
Don't write Azure exports into _unitystorage: Use a clean ADLS prefix for externally generated files and expose it via an external location/volume.
MonthToDate does not mean one file per day: It means a refreshed snapshot for the month. Design ingestion accordingly.
Expect previous-month refreshes: During the first five days of a new month, Azure may regenerate the previous month's cost export to capture late charges.
Separate raw ingestion from financial reconciliation: Raw files should remain auditable.
Deduplication/reconciliation belongs downstream.
Storage-account metrics aren't enough for chargeback: UsedCapacity tells you how large the account is. Blob Inventory tells you what is inside it.
Tags are worth enforcing early: Retrofitting ownership is much harder than carrying from the beginning.