Lab: A Fast Dashboard That Respects Access Rules
Build an Apache Superset 6.1 dashboard on a PostgreSQL mart, give a regional manager a role that sees only their region through a row-level security rule, then make the charts cheap and fast with a pre-aggregated table and a result cache, and see what happens to the cache when the data changes.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start PostgreSQL and load the mart
- Step 2: Give Superset a read-only login
- Step 3: Configure and initialise Superset
- Step 4: Start Superset
- Step 5: Register the mart and build the dashboard
- Step 6: Ask for chart data the way the dashboard does
- Step 7: A role that sees only the North region
- Step 8: Caching that respects the rules
- Step 9: Measure what pre-aggregation saves
- Step 10: Watch the cache serve stale numbers
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Serving & BI
- Who Consumes Data and How It Reaches Them Concept · 20 min
- One Definition per Metric: Building a Semantic Layer Worked example · 25 min
- Lab: A Fast Dashboard That Respects Access Rules Lab · 30 min
- Lab: Reverse ETL from a Mart to an Operational Tool Lab · 25 min
- Low-Latency Serving: Caches, Data APIs and Real-Time OLAP Worked example · 20 min
- Check: Choose and Defend a Serving Path Knowledge check · 8 questions
What you will learn
- Build a BI dashboard (for example Apache Superset or Metabase) on a mart with filters, row-level access for viewer roles, and caching or pre-aggregation that keeps it within a stated latency and query-cost budget.
01. Goal and setup
A dashboard must show each viewer only the rows they may see, answer quickly enough that people keep using it, and not cost a fortune in warehouse queries. In this lab you build one that does all three with Apache Superset, an open-source BI (business intelligence) tool, on a small PostgreSQL mart.
You will load two million orders, connect Superset with a read-only login, build a dashboard, and add a role for the North region's manager. A row-level security (RLS) rule makes Superset add region = 'North' to every query this role runs. Then you measure what pre-aggregation and caching save, and see a cache serve stale numbers.
You need Docker, curl and Python 3.11 or 3.12 (Superset 6.1 supports 3.10 to 3.12). The lab was tested with Apache Superset 6.1.0, PostgreSQL 17.11 in the postgres:17-alpine image and Python 3.11. Superset is installed with pip so that every step is a command you can check; the official Docker Compose setup works too. Each Superset release pins its dependencies in a requirements file. Install with it as a constraints file (-c): a plain pip install takes the newest version of every dependency, and in our test that broke superset db upgrade.
mkdir dashboard-lab && cd dashboard-lab
python3.11 -m venv .venv && source .venv/bin/activate
curl -sL https://raw.githubusercontent.com/apache/superset/6.1.0/requirements/base.txt \
| grep -E '^[A-Za-z0-9_.-]+==' > constraints.txt
pip install "apache-superset==6.1.0" psycopg2-binary -c constraints.txtCreate the files below as you reach each step. They all live in dashboard-lab/.
dashboard-lab/
├── env.sh settings for every terminal
├── seed.sql step 1: the mart (fact table and daily aggregate)
├── reader.sql step 2: a read-only login for Superset
├── superset_config.py step 3: secret key, metadata database, chart cache
├── client.py step 5: a small client for Superset's REST API
├── setup_dashboard.py step 5: database, datasets, charts, dashboard
├── query.py step 6: asks for chart data as a given user
├── add_region_role.py step 7: role, user and row-level security rule
├── cost.sql step 9: rows read by each version of the chart
└── late_orders.sql step 10: a late load that changes the data# Source this file in every terminal you use for the lab: source env.sh
export SUPERSET_HOME="$PWD/superset-home"
export SUPERSET_CONFIG_PATH="$PWD/superset_config.py"
export SUPERSET_SECRET_KEY="lab-only-secret-change-me-7d41c2a9e0"
export FLASK_APP=superset
export ADMIN_PASSWORD="admin-lab-pass" MANAGER_PASSWORD="north-lab-pass"
# The read-only login that Superset uses to query the mart.
export MART_URI="postgresql+psycopg2://superset_reader:[email protected]:55433"
export MART_URI="$MART_URI/shop"02. Step 1: Start PostgreSQL and load the mart
The mart has a fact table with one row per order and a pre-aggregated table with one row per day, region and category. Pre-aggregation means computing the sums once, when the data loads, so that each chart reads a few thousand rows instead of millions. The values come from arithmetic on the order number rather than random(), so everyone gets the same totals. Start the database, wait until it accepts TCP connections, then load the data.
-- Two million orders for 2026, the same on every machine (no random()).
SET client_min_messages = warning;
CREATE SCHEMA IF NOT EXISTS marts;
DROP TABLE IF EXISTS marts.fct_orders;
CREATE TABLE marts.fct_orders AS
SELECT i AS order_id,
DATE '2026-01-01' + (i % 365) AS order_date,
(ARRAY['North', 'South', 'East', 'West'])[1 + (i * 7) % 4] AS region,
(ARRAY['Books', 'Games', 'Garden', 'Kitchen', 'Toys'])[1 + (i / 365) % 5]
AS category,
round((5 + (i * 37) % 9500 / 100.0)::numeric, 2) AS amount
FROM generate_series(1, 2000000) AS i;
ANALYZE marts.fct_orders;
-- The pre-aggregated table the dashboard reads: one row per day, region, category.
DROP TABLE IF EXISTS marts.agg_daily_sales;
CREATE TABLE marts.agg_daily_sales AS
SELECT order_date, region, category,
count(*) AS orders, sum(amount) AS revenue
FROM marts.fct_orders
GROUP BY order_date, region, category;
ANALYZE marts.agg_daily_sales;
SELECT 'fct_orders' AS table_name, count(*) AS row_count FROM marts.fct_orders
UNION ALL
SELECT 'agg_daily_sales', count(*) FROM marts.agg_daily_sales;docker run -d --name dashboard-lab-pg -e POSTGRES_USER=lab -e POSTGRES_PASSWORD=lab \
-e POSTGRES_DB=shop -p 127.0.0.1:55433:5432 postgres:17-alpine
until docker exec dashboard-lab-pg pg_isready -h 127.0.0.1 -U lab -q; do sleep 1; done
docker exec -i dashboard-lab-pg psql -U lab -d shop -q < seed.sql table_name | row_count
-----------------+-----------
fct_orders | 2000000
agg_daily_sales | 7300
(2 rows)03. Step 2: Give Superset a read-only login
Superset connects to the database with one login and runs every viewer's queries through it. That login should be able to read the marts and do nothing else. If it could write, then a bug, or a careless user with SQL access, could change the data that everyone sees. This is the principle of least privilege: grant only what the job needs.
-- A read-only login for Superset: it can read the marts and nothing else.
CREATE ROLE superset_reader LOGIN PASSWORD 'reader-lab-pass';
GRANT USAGE ON SCHEMA marts TO superset_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA marts TO superset_reader;docker exec -i dashboard-lab-pg psql -U lab -d shop < reader.sqlCREATE ROLE
GRANT
GRANT04. Step 3: Configure and initialise Superset
Superset keeps its own metadata database for users, roles, charts and dashboards: SQLite is enough for a lab, production uses PostgreSQL or MySQL. DATA_CACHE_CONFIG turns on the cache for chart results; the default, NullCache, caches nothing. Here results go to files and expire after six hours; a shared deployment uses Redis so that every web server sees the same cache. Then create the metadata tables, an admin user and the built-in roles.
# Lab settings for Superset 6.1. Never reuse this secret outside the lab.
import os
SECRET_KEY = os.environ["SUPERSET_SECRET_KEY"]
SQLALCHEMY_DATABASE_URI = f"sqlite:///{os.environ['SUPERSET_HOME']}/superset.db"
# Cache chart results on disk for 6 hours (the mart is rebuilt once a day).
DATA_CACHE_CONFIG = {
"CACHE_TYPE": "FileSystemCache",
"CACHE_DIR": os.path.join(os.environ["SUPERSET_HOME"], "chart-cache"),
"CACHE_DEFAULT_TIMEOUT": 6 * 60 * 60,
}source env.sh
superset db upgrade
superset fab create-admin --username admin --firstname Ada --lastname Admin \
--email [email protected] --password "$ADMIN_PASSWORD" 2>&1 | grep created
superset initAdmin User admin created.05. Step 4: Start Superset
Start the development server in a second terminal and leave it running. It listens only on 127.0.0.1, so nothing outside your machine can reach it. You can also open http://127.0.0.1:8088 and log in as admin to watch the next steps appear.
cd dashboard-lab && source .venv/bin/activate && source env.sh
superset run -h 127.0.0.1 -p 8088 --with-threads
curl -s http://127.0.0.1:8088/health; echoOK06. Step 5: Register the mart and build the dashboard
A script can be re-run and reviewed, unlike clicks in the interface. client.py logs in through the REST API, which returns an access token, and fetches a CSRF token, which Superset requires on requests that change something. setup_dashboard.py registers the database with the read-only URI, adds both tables as datasets (Superset's name for a table it can chart), and creates a dashboard with two table charts that read the aggregate.
"""A small Superset REST client for the lab (Superset 6.1)."""
import os
import requests
BASE = os.environ.get("SUPERSET_URL", "http://127.0.0.1:8088")
def login(username, password):
s = requests.Session()
r = s.post(f"{BASE}/api/v1/security/login", timeout=30, json={
"username": username, "password": password,
"provider": "db", "refresh": False})
r.raise_for_status()
s.headers["Authorization"] = f"Bearer {r.json()['access_token']}"
csrf = s.get(f"{BASE}/api/v1/security/csrf_token/", timeout=30)
csrf.raise_for_status()
s.headers["X-CSRFToken"] = csrf.json()["result"]
s.headers["Referer"] = BASE
return s
def call(s, method, path, **kwargs):
r = s.request(method, f"{BASE}{path}", timeout=60, **kwargs)
if r.status_code >= 400:
try:
body = r.json()
detail = body.get("message") or body["errors"][0]["message"]
except (ValueError, KeyError, IndexError):
detail = r.text[:200]
raise SystemExit(f"{method} {path} -> HTTP {r.status_code}: {detail}")
return r.json()"""Register the mart as a database and two datasets, then build a dashboard."""
import json
import os
from client import call, login
READER_URI = os.environ["MART_URI"]
s = login("admin", os.environ["ADMIN_PASSWORD"])
db = call(s, "POST", "/api/v1/database/",
json={"database_name": "shop", "sqlalchemy_uri": READER_URI})["id"]
ds = {}
for table in ("agg_daily_sales", "fct_orders"):
ds[table] = call(s, "POST", "/api/v1/dataset/", json={
"database": db, "schema": "marts", "table_name": table})["id"]
print("datasets:", ds)
dash = call(s, "POST", "/api/v1/dashboard/",
json={"dashboard_title": "Sales by region"})["id"]
revenue = {"expressionType": "SQL", "sqlExpression": "SUM(revenue)",
"label": "revenue"}
charts = {
"Revenue by region": {"viz_type": "table", "groupby": ["region"],
"metrics": [revenue], "row_limit": 100},
"Revenue by category": {"viz_type": "table", "groupby": ["category"],
"metrics": [revenue], "row_limit": 100},
}
for name, params in charts.items():
params["datasource"] = f"{ds['agg_daily_sales']}__table"
chart = call(s, "POST", "/api/v1/chart/", json={
"slice_name": name, "viz_type": params["viz_type"],
"datasource_id": ds["agg_daily_sales"], "datasource_type": "table",
"params": json.dumps(params), "dashboards": [dash]})["id"]
print("chart:", chart, name)
print("dashboard:", dash)python setup_dashboard.pydatasets: {'agg_daily_sales': 1, 'fct_orders': 2}
chart: 1 Revenue by region
chart: 2 Revenue by category
dashboard: 107. Step 6: Ask for chart data the way the dashboard does
When a browser shows a chart, it sends a query context to /api/v1/chart/data: the dataset, the columns to group by, the metrics and any filters. Superset turns it into SQL, runs it, and returns rows. query.py sends the same request as any user you choose, so you can see exactly what each viewer gets. Run it twice as the admin, then once with the category filter that a dashboard filter would add.
"""Ask Superset for chart data as a given user, the way a dashboard does."""
import argparse
import time
from client import call, login
p = argparse.ArgumentParser()
p.add_argument("user")
p.add_argument("password")
p.add_argument("--dataset", type=int, default=1)
p.add_argument("--by", default="region")
p.add_argument("--metric", default="SUM(revenue)", help="SQL for the revenue")
p.add_argument("--category", help="optional dashboard filter")
p.add_argument("--sql", action="store_true", help="print the SQL Superset ran")
p.add_argument("--timing", action="store_true", help="print the response time")
p.add_argument("--force", action="store_true", help="skip the cache and re-run")
a = p.parse_args()
s = login(a.user, a.password)
filters = [{"col": "category", "op": "==", "val": a.category}] if a.category else []
body = {
"datasource": {"id": a.dataset, "type": "table"},
"queries": [{
"columns": [a.by], "filters": filters, "orderby": [[a.by, True]],
"metrics": [{"expressionType": "SQL", "label": "revenue",
"sqlExpression": a.metric}],
}],
"result_format": "json", "result_type": "full", "force": a.force,
}
start = time.perf_counter()
result = call(s, "POST", "/api/v1/chart/data", json=body)["result"][0]
seconds = time.perf_counter() - start
if a.sql:
print(result["query"].strip())
for row in result["data"]:
print(f"{row[a.by]:<8} {row['revenue']:>14,.2f}")
print("rows:", result["rowcount"], "| cached:", bool(result["is_cached"]))
if a.timing:
print(f"response time: {seconds:.2f} s")python query.py admin "$ADMIN_PASSWORD"
python query.py admin "$ADMIN_PASSWORD"East 26,249,245.00
North 26,239,340.00
South 26,254,220.00
West 26,244,270.00
rows: 4 | cached: False
East 26,249,245.00
North 26,239,340.00
South 26,254,220.00
West 26,244,270.00
rows: 4 | cached: TrueThe second request was served from the cache: Superset found a stored result under the same cache key, a hash of everything that defines the query. A filter changes the query, so it changes the key and misses the cache the first time.
python query.py admin "$ADMIN_PASSWORD" --category BooksEast 5,249,351.40
North 5,247,054.40
South 5,250,354.90
West 5,248,442.90
rows: 4 | cached: False08. Step 7: A role that sees only the North region
Superset's built-in Gamma role is meant for people who consume dashboards: it gives the menus and dashboard views but no data. You add data access with a second role. add_region_role.py creates north_viewer with access to the aggregate dataset only, a user who has both roles, and an RLS rule. A Regular RLS rule adds its clause to the WHERE of every query from the roles it lists. Rules that share a group key are combined with OR, and rules in different groups with AND. A Base rule works the other way round: it applies to everyone except the listed roles, which makes it useful as a deny-by-default rule such as 1 = 0. The script uses the dataset id 1 from step 5.
"""Create a viewer role that sees only one region, and a user that has it."""
import os
import sys
from client import call, login
region = sys.argv[1] # for example North
role_name = f"{region.lower()}_viewer"
s = login("admin", os.environ["ADMIN_PASSWORD"])
def find_permissions(wanted):
found, page = {}, 0
while True:
r = call(s, "GET", "/api/v1/security/permissions-resources/"
f"?q=(page_size:100,page:{page})")
for pv in r["result"]:
key = (pv["permission"]["name"], pv["view_menu"]["name"])
if key in wanted:
found[key] = pv["id"]
if not r["result"]: # past the last page
return [found[k] for k in wanted] # KeyError if one is missing
page += 1
# Gamma gives the menus and dashboards; this role adds one dataset only.
wanted = [("datasource_access", "[shop].[agg_daily_sales](id:1)")]
gamma = next(r["id"] for r in call(s, "GET", "/api/v1/security/roles/")["result"]
if r["name"] == "Gamma")
role = call(s, "POST", "/api/v1/security/roles/", json={"name": role_name})["id"]
call(s, "POST", f"/api/v1/security/roles/{role}/permissions",
json={"permission_view_menu_ids": find_permissions(wanted)})
user = call(s, "POST", "/api/v1/security/users/", json={
"first_name": region, "last_name": "Manager", "active": True,
"username": f"{region.lower()}_manager", "email": f"{region.lower()}@example.com",
"password": os.environ["MANAGER_PASSWORD"], "roles": [gamma, role]})["id"]
rls = call(s, "POST", "/api/v1/rowlevelsecurity/", json={
"name": f"{role_name} rows", "filter_type": "Regular", "tables": [1],
"roles": [role], "group_key": "region", "clause": f"region = '{region}'"})["id"]
print(f"role {role_name} id={role}, user id={user}, rls rule id={rls}")python add_region_role.py Northrole north_viewer id=6, user id=2, rls rule id=1Now ask for the same chart as the manager, and print the SQL that Superset ran. The manager did not choose the filter and cannot remove it. It applies to every chart and filter on this dataset.
python query.py north_manager "$MANAGER_PASSWORD" --sqlSELECT region AS region, SUM(revenue) AS revenue
FROM marts.agg_daily_sales
WHERE (region = 'North') GROUP BY region ORDER BY region ASC
LIMIT 50000;
North 26,239,340.00
rows: 1 | cached: FalseGroup by category instead, and the five rows add up to the North total of 26,239,340.00: the rule filters rows before they are grouped, whatever the chart asks for. Then try the fact table, which the role was never given.
python query.py north_manager "$MANAGER_PASSWORD" --by category
python query.py north_manager "$MANAGER_PASSWORD" --dataset 2 2>&1 | fold -w 80Books 5,247,054.40
Games 5,249,605.40
Garden 5,247,757.40
Kitchen 5,248,949.40
Toys 5,245,973.40
rows: 5 | cached: False
POST /api/v1/chart/data -> HTTP 403: This endpoint requires the datasource 2, da
tabase or `all_datasource_access` permission09. Step 8: Caching that respects the rules
Run the manager's chart again. It is now cached. But in step 7, the manager's first request missed, although the admin had cached the same chart in step 6. In Superset 6.1, the cache key includes the RLS clauses that apply to the viewer, along with the query and the time the dataset was last changed. Two viewers with different rules can never receive each other's cached rows. A home-made cache in front of a database needs the same property, or the cache itself leaks data.
python query.py north_manager "$MANAGER_PASSWORD"North 26,239,340.00
rows: 1 | cached: True10. Step 9: Measure what pre-aggregation saves
Response times vary between runs, so first measure the work, which does not. EXPLAIN (ANALYZE) runs a query and reports how many rows each step produced. Turning off parallel workers keeps the plan the same on every machine, and grep keeps the line that scans the table.
-- How many rows does each version of the chart read? (one process, no timings)
SET max_parallel_workers_per_gather = 0;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT region, sum(amount) FROM marts.fct_orders GROUP BY region;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT region, sum(revenue) FROM marts.agg_daily_sales GROUP BY region;docker exec -i dashboard-lab-pg psql -U lab -d shop < cost.sql | grep "Seq Scan" -> Seq Scan on fct_orders (actual rows=2000000 loops=1)
-> Seq Scan on agg_daily_sales (actual rows=7300 loops=1)The aggregate answers the same question by reading 7,300 rows instead of two million. In a cloud warehouse that bills by the data each query scans, the smaller read is also a much smaller bill. A pre-aggregate is only useful if it agrees with its source, so check that the fact table gives the same totals.
python query.py admin "$ADMIN_PASSWORD" --dataset 2 --metric "SUM(amount)"East 26,249,245.00
North 26,239,340.00
South 26,254,220.00
West 26,244,270.00
rows: 4 | cached: FalseNow time the fact table and the aggregate with the cache skipped (--force), then the aggregate from the cache. Your times will differ. With two million rows every version is fast; the gap grows with the data, which is why a dashboard has a latency budget, such as "every chart within two seconds", checked whenever it changes.
python query.py admin "$ADMIN_PASSWORD" --dataset 2 --metric "SUM(amount)" \
--force --timing | tail -n 2
python query.py admin "$ADMIN_PASSWORD" --force --timing | tail -n 2
python query.py admin "$ADMIN_PASSWORD" --timing | tail -n 2rows: 4 | cached: False
response time: 0.89 s
rows: 4 | cached: False
response time: 0.60 s
rows: 4 | cached: True
response time: 0.22 s11. Step 10: Watch the cache serve stale numbers
Two late North orders arrive and the nightly job rebuilds the aggregate. Load the change and ask again, then ask with --force, which is what the dashboard's "Force refresh" does.
-- Late-arriving orders, then the nightly rebuild of the aggregate.
INSERT INTO marts.fct_orders VALUES
(2000001, DATE '2026-12-31', 'North', 'Books', 100.00),
(2000002, DATE '2026-12-31', 'North', 'Toys', 60.00);
TRUNCATE marts.agg_daily_sales;
INSERT INTO marts.agg_daily_sales
SELECT order_date, region, category, count(*), sum(amount)
FROM marts.fct_orders GROUP BY order_date, region, category;docker exec -i dashboard-lab-pg psql -U lab -d shop -q < late_orders.sql
python query.py north_manager "$MANAGER_PASSWORD"
python query.py north_manager "$MANAGER_PASSWORD" --forceNorth 26,239,340.00
rows: 1 | cached: True
North 26,239,500.00
rows: 1 | cached: FalseThe first answer is 160.00 short and would stay wrong until the six-hour timeout. Set the cache lifetime from how often the data changes (Superset also accepts a timeout per chart, dataset or database), and make the load job refresh the cache when it finishes. Each RLS role has its own cache keys, so a warm-up run as the admin does not warm the managers' charts. Finally, stop Superset with Ctrl+C and run docker rm -f -v dashboard-lab-pg; -v also removes the data volume.
12. Check your understanding
13. Apply it
This is the dashboard part of the skill practice. Move it onto the star schema from your batch project:
- Build the aggregate at the grain your charts need, add a native filter for each question the dashboard answers, and write the latency budget next to it.
- Give two regional roles their own RLS rules, add a Base rule
1 = 0for everyone except the admin, and prove withquery.pythat a user without a regional role sees no rows. - Refresh the cache at the end of each load, and show with
--timingthat the slowest chart meets the budget.
14. Review prompt
Without looking back, explain: why Superset connects with a read-only login; what a Regular RLS rule adds to a query and how group keys combine rules; why the cache key must include the viewer's access rules; why a pre-aggregate must be checked against its source; and why a cached chart can be wrong after a reload.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.