If you’re using a standard Databricks App, it will run 24/7, incurring costs even when no-one is using it. Using the minimum compute specification (a medium app), this comes to about $350 USD per month per app (Pricing Calculator Page | Databricks). For Apps that have intermittent or unpredictable usage, ideally there should be a way for the App to be available when the user needs it to be, without having to pay when the user does not. It is theoretically possible to have users turn on and off their own Databricks as needed. This approach however, either requires elevated access or a request to IT to facilitate, and risks human error in the process.
At the time of writing this blog, there is no native way in Databricks to:
To solve this problem we implemented the following:
We had built a Databricks App for one of our clients to optimise a business process, however they only needed to use the App a few hours per week. It seemed unnecessary to pay the full $350 per month for constant compute uptime. By letting users safely start and stop the App on demand, and adding an idle auto-stop, we were able to limit the uptime to more closely match (and only pay for) the usage the business actually needed. This came to about $30 per month, a 91% reduction from the default behaviour of leaving the App running 24/7!
To get started straight away, head to the repo: Drop-Database-Cascade/DBX-App-Cost-Saving (sample code to implement Databricks App cost-saving functionality: on-demand start and stop, and idle auto-stop).
Databricks Jobs can call the Databricks Apps API to start and stop apps programmatically. The main benefit of using Jobs is that App users only need ‘Can Manage Run’ on the Start App and Stop App jobs, rather than ‘Can Manage’ on the App itself.
app_name (the name of the app to start), and one optional parameter, warmup_seconds, which delays job completion if your app takes a bit longer to be ready for users after starting up.app_name (the name of the app to stop).The second part of the solution handles the case where a user starts the App but forgets to stop it afterwards. Rather than leaving the App running indefinitely, we track user activity and automatically stop the App once it has been idle for a defined period. Our App’s backend used FastAPI, so we implemented the activity tracking as a small ASGI middleware. We wanted the App to stop automatically if no user activity had been detected for 30 minutes, to avoid costs when end users forget to stop it. We also added a fail-safe that stops the App after 6 hours of continuous running, to catch an unexpected process keeping it awake overnight or over a weekend.
The core of it is a timestamp and a middleware that updates it:
class IdleTracker:
def __init__(self):
self._last = time.monotonic()
def touch(self):
self._last = time.monotonic()
def idle_seconds(self):
return time.monotonic() - self._last
class ActivityMiddleware:
"""ASGI middleware that records HTTP requests and WebSocket messages as activity.
ignore_path_prefixes: paths that should NOT count as activity, such as health
checks or endpoints your frontend polls automatically. If a page polls the
backend while a tab is open, the app will never look idle unless you list
that endpoint here.
require_user_header: if True, only requests carrying the user identity
headers added by the Databricks Apps proxy (X-Forwarded-Email /
X-Forwarded-User) count. Check those headers reach your app first.
"""
def __init__(
self,
app,
tracker: IdleTracker,
ignore_path_prefixes: tuple[str, ...] = ("/health",),
require_user_header: bool = False,
) -> None:
self.app = app
self.tracker = tracker
self.ignore_path_prefixes = tuple(ignore_path_prefixes)
self.require_user_header = require_user_header
def _is_user_traffic(self, scope) -> bool:
if scope.get("path", "").startswith(self.ignore_path_prefixes):
return False
if self.require_user_header:
names = {k.lower() for k, _ in scope.get("headers") or []}
return b"x-forwarded-email" in names or b"x-forwarded-user" in names
return True
async def __call__(self, scope, receive, send):
if scope["type"] not in ("http", "websocket") or not self._is_user_traffic(scope):
await self.app(scope, receive, send)
return
self.tracker.touch()
if scope["type"] == "websocket":
original_receive = receive
async def receive(): # noqa: F811 - wraps the original receive
message = await original_receive()
if message["type"] == "websocket.receive":
self.tracker.touch()
return message
try:
await self.app(scope, receive, send)
finally:
# Also record the end, so a long request can't be cut off mid-flight.
self.tracker.touch()
A background task compares that to the limit and stops the App via the Databricks SDK:
async def stop_when_idle(app_name, idle_minutes, tracker):
while True:
await asyncio.sleep(60)
if tracker.idle_seconds() >= idle_minutes * 60:
await asyncio.to_thread(WorkspaceClient().apps.stop, app_name)
return
The full module in the repo wraps this in an AutoStop class, so integrating it into a FastAPI app takes a few lines:
auto_stop = AutoStop() # reads its settings from environment variables
@asynccontextmanager
async def lifespan(app):
auto_stop.start()
try:
yield
finally:
await auto_stop.shutdown()
app = FastAPI(lifespan=lifespan)
app.add_middleware(
ActivityMiddleware,
tracker=auto_stop.tracker,
ignore_path_prefixes=("/health",),
)
The idle limit and the hard cap are set with the AUTO_STOP_IDLE_MINUTES and AUTO_STOP_MAX_HOURS environment variables, in app.yaml or, if you deploy with DABs, in the App’s config in databricks.yml:
env:
- name: AUTO_STOP_IDLE_MINUTES
value: "30" # "0" disables
- name: AUTO_STOP_MAX_HOURS
value: "6" # "0" disables
ignore_path_prefixes, or the App may never stop.uvicorn main:app runs one, --workers 4 runs four). The idle clock lives in each process’s memory, so with several workers each keeps its own. A worker that happens to get no requests for 30 minutes can then stop the whole App while the others are still serving users. One worker is usually plenty for an internal App, since FastAPI handles many concurrent users asynchronously. If you do need several, store the last-activity time somewhere they all share, such as a small file on the App’s local disk.Only two identities need ‘Can Manage’ on the App; end users never do.
The job run-as identity and the App’s service principal can be the same account. If you deploy with Databricks Asset Bundles (DABs), these grants can be defined in the databricks.yml file.
While researching this problem, I came across a great article by Maksim Pachkouski on scheduling fixed start and stop times for Databricks Apps: Cut Databricks Apps Costs by 76%: Automate Start/Stop (nearly scale to zero) | by Maksim Pachkouski Databricks MVP | Dev Genius. It didn’t quite fit our use case, as our end users used the App far less frequently and on an ad hoc basis, but his approach offers great cost savings for many Databricks Apps.
I suspect Databricks will eventually add scale-to-zero and auto-terminate for Databricks App compute, which will make cost management even easier. For now, the approach in this blog can save a significant amount in the short term.
Here at Advancing Analytics we’re doing a lot of work with Databricks Apps as part of our AI, Engineering and Analytics capabilities. For more articles and content, see our blog posts here and our YouTube channel here.