Outlining Dash app with server-side caching
The plan is to deliver a fully working Dash app code that uses flask_caching.Cache to memoize a heavy computation function called by a callback triggered by a dropdown. This ensures server-side caching avoids repeating costly aggregation for identical inputs. Next, I'll produce the complete code following this pattern.
Below is a minimal but complete Dash app that demonstrates a dropdown-controlled graph whose “heavy” computation is memoized on the server side with flask-caching. Identical dropdown selections will be served from cache instead of recomputing.
import time
import pandas as pd
import plotly.express as px
from flask_caching import Cache
from dash import Dash, dcc, html, Input, Output
# -------------------------------------------------------
# Build a Dash app and expose its Flask server
# -------------------------------------------------------
app = Dash(__name__)
server = app.server # Expose for gunicorn / uWSGI, etc.
# -------------------------------------------------------
# Configure caching (in this case, in-memory)
# Other cache types: Redis, filesystem, Memcached, etc.
# -------------------------------------------------------
cache = Cache(server, config={
"CACHE_TYPE": "simple", # For production, consider "RedisCache"
"CACHE_DEFAULT_TIMEOUT": 300 # seconds
})
# -------------------------------------------------------
# Example dataset (Plotly’s gapminder)
# -------------------------------------------------------
df = px.data.gapminder()
# -------------------------------------------------------
# Heavy aggregation function
# Memoized by Flask-Caching to avoid redoing the same work
# -------------------------------------------------------
@cache.memoize(timeout=300) # cache for 5 minutes
def heavy_aggregation(continent: str):
# Simulate a heavy/expensive operation
time.sleep(2) # remove/adjust in production
# “Heavy” aggregation: filter then groupby
filtered = df[df["continent"] == continent]
summary = (
filtered
.groupby("year")
.agg({"lifeExp": "mean", "pop": "sum"})
.reset_index()
)
# Build a figure
fig = px.line(
summary,
x="year",
y="lifeExp",
title=f"Mean Life Expectancy over Time: {continent}",
labels={"lifeExp": "Mean Life Expectancy"},
markers=True,
)
fig.update_traces(line_shape="spline")
return fig
# -------------------------------------------------------
# App layout
# -------------------------------------------------------
app.layout = html.Div(
style={"width": "80%", "margin": "0 auto", "font-family": "Arial"},
children=[
html.H2("Continent Life Expectancy (Cached)"),
html.P("Select a continent to run the 'heavy' aggregation."),
dcc.Dropdown(
id="continent-dropdown",
options=[{"label": c, "value": c} for c in sorted(df["continent"].unique())],
value="Asia",
clearable=False,
style={"width": "50%"}
),
html.Br(),
dcc.Graph(id="lifeexp-graph"),
html.Div(
"Tip: Selecting the same continent again will be served from cache.",
style={"marginTop": "10px", "fontStyle": "italic"}
),
]
)
# -------------------------------------------------------
# Callback
# -------------------------------------------------------
@app.callback(
Output("lifeexp-graph", "figure"),
Input("continent-dropdown", "value")
)
def update_graph(continent):
# Call the memoized heavy function
return heavy_aggregation(continent)
# -------------------------------------------------------
# Entry point
# -------------------------------------------------------
if __name__ == "__main__":
# For production, set debug=False
app.run_server(debug=True)
How it works:
heavy_aggregation is decorated with @cache.memoize(...). The cache key automatically includes the function name and its arguments (in this case, continent), so identical calls reuse the cached result.
- The callback simply calls
heavy_aggregation(continent) and returns the cached figure to the dcc.Graph.
- In a real application, you’d place your expensive queries or large data processing inside the memoized function; here it’s simulated with
time.sleep(2) and a groupby on the gapminder dataset.
- The
CACHE_TYPE="simple" uses in-memory caching. Swap to Redis or filesystem for multi-process/production workloads.