Apply production-ready Databricks SDK patterns for Python and REST API.
Use when implementing Databricks integrations, refactoring SDK usage,
or establishing team coding standards for Databricks.
Trigger with phrases like "databricks SDK patterns", "databricks best practices",
"databricks code patterns", "idiomatic databricks".
Apply production-ready Databricks SDK patterns for Python and REST API.
Use when implementing Databricks integrations, refactoring SDK usage,
or establishing team coding standards for Databricks.
Trigger with phrases like "databricks SDK patterns", "databricks best practices",
"databricks code patterns", "idiomatic databricks".
allowed-tools
Read, Write, Edit
version
1.0.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
compatible-with
claude-code, codex, openclaw
tags
["saas","databricks","api","python"]
Databricks SDK Patterns
Overview
Production-ready patterns for the Databricks Python SDK (databricks-sdk). Covers singleton client initialization, typed error handling, cluster lifecycle management, type-safe job construction, and pagination. Uses real SDK exception classes and API shapes.
Prerequisites
databricks-sdk>=0.20.0 installed
Authentication configured (see databricks-install-auth)
Python 3.10+
Instructions
Step 1: Singleton Client with Profile Support
Each WorkspaceClient holds an HTTP session and re-authenticates. Cache instances.
from databricks.sdk import WorkspaceClient, AccountClient
from functools import lru_cache
@lru_cache(maxsize=4)defget_client(profile: str = "DEFAULT") -> WorkspaceClient:
"""Cached WorkspaceClient — one per profile."""return WorkspaceClient(profile=profile)
@lru_cache(maxsize=1)defget_account_client() -> AccountClient:
"""Account-level client for multi-workspace operations."""return AccountClient(
host="https://accounts.cloud.databricks.com",
account_id="00000000-0000-0000-0000-000000000000",
)
# Usage
w = get_client()
w_prod = get_client("production")
Step 2: Structured Error Handling
The SDK raises typed exceptions from databricks.sdk.errors. Distinguish transient (retryable) from permanent failures.
The SDK auto-paginates via iterators. Wrap for progress tracking and filtering.
from typing import Iterator
defcollect_with_progress(iterator: Iterator, label: str, batch_log: int = 100) -> list:
"""Drain a paginated iterator with progress logging."""
items = []
for i, item inenumerate(iterator, 1):
items.append(item)
if i % batch_log == 0:
print(f" {label}: {i} items fetched...")
print(f" {label}: {len(items)} total")
return items
# Usage
all_jobs = collect_with_progress(w.jobs.list(), "Jobs")
all_clusters = collect_with_progress(w.clusters.list(), "Clusters")
running = [c for c in all_clusters if c.state == State.RUNNING]
print(f"Running: {len(running)}/{len(all_clusters)} clusters")
Output
Singleton WorkspaceClient with profile-based caching
Result[T] wrapper for typed, structured error handling
Context manager for ephemeral cluster lifecycle
Type-safe job builder using SDK dataclasses
Pagination helper with progress logging
Error Handling
SDK Exception
HTTP Code
Retryable
Typical Cause
NotFound
404
No
Resource deleted or wrong ID
PermissionDenied
403
No
Token lacks required scope
InvalidParameterValue
400
No
Wrong type or value in API call
ResourceAlreadyExists
409
No
Duplicate name or conflicting create
ResourceConflict
409
No
Job already running
TooManyRequests
429
Yes
Rate limit exceeded
TemporarilyUnavailable
503
Yes
Control plane overloaded
Examples
Health Check Script
w = get_client()
me = w.current_user.me()
print(f"User: {me.user_name}")
print(f"Host: {w.config.host}")
print(f"Auth: {w.config.auth_type}")
print(f"Running clusters: {sum(1for c in w.clusters.list() if c.state == State.RUNNING)}")
print(f"Jobs defined: {sum(1for _ in w.jobs.list())}")
Multi-Workspace Inventory
acct = get_account_client()
for ws in acct.workspaces.list():
ws_client = WorkspaceClient(host=f"https://{ws.deployment_name}.cloud.databricks.com")
clusters = list(ws_client.clusters.list())
running = [c for c in clusters if c.state == State.RUNNING]
print(f"{ws.workspace_name}: {len(running)} running / {len(clusters)} total")