
Most dashboards fail not because the charts are ugly but because nobody trusts the numbers or knows what to do with them. A useful dashboard starts with a decision someone needs to make, is fed by a pipeline that reconciles with finance, and shows a handful of KPIs that change behaviour. This guide walks through the whole build for a typical Kenyan retail or service business: designing KPIs, modelling sales and M-Pesa data in PostgreSQL, writing KPI views in SQL, and shipping an interactive dashboard in Python with Streamlit. The same pipeline works if you later point Power BI, Metabase or Looker Studio at it.
Key takeaways
- Design KPIs backwards from decisions: who looks at the number, how often, and what they do when it moves.
- Separate ingestion, modelling and presentation. Dashboards should read from curated views in a reporting database, never directly from production tables.
- Reconcile M-Pesa receipts against recorded sales daily; the variance itself is one of the most valuable KPIs for a business that takes mobile money.
- Use Africa/Nairobi time consistently. Mixing UTC and local time silently shifts late-evening sales into the wrong day.
- Treat phone numbers in payment data as personal data under the Kenya Data Protection Act 2019: hash or mask them before they reach the reporting layer.
Step 1: Design KPIs before touching data
Principles of good KPI design
- Tie each KPI to a decision and an owner. "Daily revenue by branch" is owned by the operations manager, who reallocates staff or stock when a branch underperforms.
- Define it precisely. Does revenue include VAT? Are refunds and M-Pesa reversals subtracted? Which timestamp decides the day? Write the definition down.
- Pair outcomes with drivers. Revenue is an outcome; orders and average basket value are drivers. Showing both tells managers why revenue moved.
- Provide context. A number alone is meaningless. Show it against the previous period, a target or the same day last week.
- Keep it small. Five to seven KPIs on the main view. Detail belongs in drill-downs.
- Match refresh to decision speed. A daily stock decision does not need a real-time feed; a fraud alert might.
KPI specification for our example
| KPI | Definition | Owner | Refresh | Action when it moves |
|---|---|---|---|---|
| Revenue (KES) | Sum of completed order totals, VAT inclusive, Nairobi calendar day | Operations manager | Hourly | Investigate branches below target |
| Orders | Count of completed orders | Branch managers | Hourly | Staffing, promotions |
| Average basket (KES) | Revenue / orders | Commercial lead | Daily | Upsell and bundle decisions |
| M-Pesa share | M-Pesa sales / revenue | Finance | Daily | Till and paybill capacity, cash handling |
| M-Pesa variance (KES) | M-Pesa received minus M-Pesa sales recorded | Finance | Daily | Reconcile missing or duplicate payments |
| Repeat payer rate | Share of payers in the last 30 days who paid on two or more days | Marketing | Weekly | Loyalty campaigns |
A good dashboard answers a decision, not just a question.
Step 2: Design the pipeline
POS / web shop DB ----(nightly + hourly incremental extract)----+
|
Safaricom Daraja C2B confirmation callbacks --(API service)------+
v
Reporting DB (PostgreSQL)
raw tables: orders, mpesa_transactions
views: kpi_daily, kpi_repeat_payers
|
v
Streamlit dashboard (or Power BI / Metabase)
behind SSO or VPN, read-only DB role
Design choices worth noting:
- Daraja callbacks for M-Pesa. The Safaricom Daraja API can notify your endpoint of C2B payments to a paybill or till. Storing each confirmation as it arrives gives you near-real-time data rather than relying on downloaded statements. Keep statement imports as a reconciliation backstop, since callbacks can be missed if your endpoint is down.
- A separate reporting database. Heavy analytical queries on the POS database during trading hours slow down checkout. Replicate or extract into a reporting database.
- Idempotent ingestion. Callbacks can be retried; extracts can be re-run. Use unique keys so duplicates are ignored.
- Hosting. A small managed PostgreSQL instance in a cloud region or a local data centre is enough for most SMEs. Latency from Nairobi to South African or European cloud regions is fine for dashboards, but keep personal data residency in mind.
Step 3: Model the data in PostgreSQL
The schema below is deliberately minimal. Amounts are stored as numeric (never floating point for money), and timestamps as timestamptz.
CREATE TABLE branches (
branch_id integer PRIMARY KEY,
name text NOT NULL,
county text NOT NULL
);
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
branch_id integer NOT NULL REFERENCES branches (branch_id),
created_at timestamptz NOT NULL,
total_kes numeric(12, 2) NOT NULL CHECK (total_kes >= 0),
payment_method text NOT NULL CHECK (payment_method IN ('mpesa', 'cash', 'card', 'airtel_money')),
status text NOT NULL CHECK (status IN ('completed', 'refunded', 'void'))
);
CREATE TABLE mpesa_transactions (
trans_id text PRIMARY KEY, -- M-Pesa receipt number, unique
trans_time timestamptz NOT NULL,
amount numeric(12, 2) NOT NULL,
bill_ref text, -- account reference entered by the customer
branch_id integer REFERENCES branches (branch_id),
payer_hash text, -- salted hash of the phone number, never the raw MSISDN
status text NOT NULL DEFAULT 'completed'
CHECK (status IN ('completed', 'reversed'))
);
CREATE INDEX orders_created_at_idx ON orders (created_at);
CREATE INDEX mpesa_trans_time_idx ON mpesa_transactions (trans_time);
Ingestion from the callback service then becomes a safe upsert. Re-delivered callbacks are ignored because trans_id is the primary key:
INSERT INTO mpesa_transactions (trans_id, trans_time, amount, bill_ref, branch_id, payer_hash)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (trans_id) DO NOTHING;
Note that Daraja's C2B payload includes TransTime as a string in the format YYYYMMDDHHmmss in East Africa Time; convert it explicitly to a timezone-aware timestamp in your service before inserting.
Step 4: Write the KPI views in SQL
Define each KPI once, in the database, so every dashboard and export uses the same logic.
CREATE OR REPLACE VIEW kpi_daily AS
WITH sales AS (
SELECT
(o.created_at AT TIME ZONE 'Africa/Nairobi')::date AS day,
o.branch_id,
COUNT(*) AS orders,
SUM(o.total_kes) AS revenue_kes,
SUM(o.total_kes) FILTER (WHERE o.payment_method = 'mpesa') AS mpesa_sales_kes
FROM orders o
WHERE o.status = 'completed'
GROUP BY 1, 2
),
mpesa AS (
SELECT
(t.trans_time AT TIME ZONE 'Africa/Nairobi')::date AS day,
t.branch_id,
SUM(t.amount) AS mpesa_received_kes,
COUNT(DISTINCT t.payer_hash) AS unique_payers
FROM mpesa_transactions t
WHERE t.status = 'completed'
GROUP BY 1, 2
)
SELECT
day,
branch_id,
COALESCE(s.orders, 0) AS orders,
COALESCE(s.revenue_kes, 0) AS revenue_kes,
ROUND(s.revenue_kes / NULLIF(s.orders, 0), 2) AS avg_basket_kes,
COALESCE(s.mpesa_sales_kes, 0) AS mpesa_sales_kes,
COALESCE(m.mpesa_received_kes, 0) AS mpesa_received_kes,
COALESCE(m.mpesa_received_kes, 0) - COALESCE(s.mpesa_sales_kes, 0) AS mpesa_variance_kes,
COALESCE(m.unique_payers, 0) AS unique_payers
FROM sales s
FULL OUTER JOIN mpesa m USING (day, branch_id);
The FULL OUTER JOIN matters: a day where M-Pesa money arrived but no M-Pesa sale was recorded is exactly the case finance needs to see.
The repeat payer rate looks at a rolling 30-day window:
CREATE OR REPLACE VIEW kpi_repeat_payers AS
WITH payer_days AS (
SELECT
payer_hash,
COUNT(DISTINCT (trans_time AT TIME ZONE 'Africa/Nairobi')::date) AS active_days
FROM mpesa_transactions
WHERE status = 'completed'
AND payer_hash IS NOT NULL
AND trans_time >= now() - interval '30 days'
GROUP BY payer_hash
)
SELECT
COUNT(*) AS payers_30d,
COUNT(*) FILTER (WHERE active_days >= 2) AS repeat_payers_30d,
ROUND(100.0 * COUNT(*) FILTER (WHERE active_days >= 2) / NULLIF(COUNT(*), 0), 1)
AS repeat_payer_rate_pct
FROM payer_days;
Finally, give the dashboard a read-only role so a bug in the presentation layer can never modify data:
CREATE ROLE dashboard_reader LOGIN PASSWORD 'use-a-secret-manager';
GRANT USAGE ON SCHEMA public TO dashboard_reader;
GRANT SELECT ON kpi_daily, kpi_repeat_payers, branches TO dashboard_reader;
Self-service analytics puts reporting in the hands of the people who act on it.
Step 5: Build the interactive dashboard
Streamlit lets a Python developer build an interactive web dashboard in a single file. Install the dependencies with pip install streamlit pandas plotly sqlalchemy psycopg2-binary, set REPORTING_DB_URL (for example postgresql+psycopg2://dashboard_reader:...@host:5432/reporting), and run streamlit run app.py.
# app.py
import os
from datetime import date, timedelta
import pandas as pd
import plotly.express as px
import streamlit as st
from sqlalchemy import create_engine, text
st.set_page_config(page_title="Sales and M-Pesa KPIs", layout="wide")
@st.cache_resource
def get_engine():
return create_engine(os.environ["REPORTING_DB_URL"], pool_pre_ping=True)
@st.cache_data(ttl=600) # cache query results for 10 minutes
def load_daily(start: date, end: date) -> pd.DataFrame:
sql = text("""
SELECT k.day, b.name AS branch, k.orders, k.revenue_kes,
k.mpesa_sales_kes, k.mpesa_received_kes, k.mpesa_variance_kes
FROM kpi_daily k
JOIN branches b USING (branch_id)
WHERE k.day BETWEEN :start AND :end
ORDER BY k.day
""")
with get_engine().connect() as conn:
df = pd.read_sql(sql, conn, params={"start": start, "end": end})
num_cols = ["revenue_kes", "mpesa_sales_kes", "mpesa_received_kes", "mpesa_variance_kes"]
df[num_cols] = df[num_cols].astype(float)
return df
def totals(df: pd.DataFrame) -> dict:
revenue = df["revenue_kes"].sum()
orders = df["orders"].sum()
return {
"revenue": revenue,
"orders": orders,
"basket": revenue / orders if orders else 0.0,
"mpesa_share": df["mpesa_sales_kes"].sum() / revenue if revenue else 0.0,
"variance": df["mpesa_variance_kes"].sum(),
}
def pct_change(current: float, previous: float) -> str | None:
return f"{(current - previous) / previous:+.1%}" if previous else None
# Sidebar filters
today = date.today()
period = st.sidebar.date_input("Period", value=(today - timedelta(days=29), today))
if not isinstance(period, tuple) or len(period) != 2:
st.stop() # wait until the user has picked both dates
start, end = period
prev_end = start - timedelta(days=1)
prev_start = prev_end - (end - start)
current = load_daily(start, end)
previous = load_daily(prev_start, prev_end)
branches = sorted(current["branch"].unique())
selected = st.sidebar.multiselect("Branches", branches, default=branches)
current = current[current["branch"].isin(selected)]
previous = previous[previous["branch"].isin(selected)]
# KPI tiles with comparison to the previous period of equal length
cur, prev = totals(current), totals(previous)
st.title("Sales and M-Pesa performance")
c1, c2, c3, c4, c5 = st.columns(5)
c1.metric("Revenue", f"KES {cur['revenue']:,.0f}", pct_change(cur["revenue"], prev["revenue"]))
c2.metric("Orders", f"{cur['orders']:,}", pct_change(cur["orders"], prev["orders"]))
c3.metric("Avg basket", f"KES {cur['basket']:,.0f}", pct_change(cur["basket"], prev["basket"]))
c4.metric("M-Pesa share", f"{cur['mpesa_share']:.0%}")
c5.metric("M-Pesa variance", f"KES {cur['variance']:,.0f}",
help="M-Pesa received minus M-Pesa sales recorded. Should be close to zero.")
# Revenue trend by branch
trend = current.groupby(["day", "branch"], as_index=False)["revenue_kes"].sum()
fig = px.line(trend, x="day", y="revenue_kes", color="branch",
labels={"revenue_kes": "Revenue (KES)", "day": ""})
st.plotly_chart(fig, use_container_width=True)
# Reconciliation exceptions: days where variance exceeds KES 500
exceptions = current[current["mpesa_variance_kes"].abs() > 500]
st.subheader("Reconciliation exceptions")
st.dataframe(exceptions[["day", "branch", "mpesa_sales_kes", "mpesa_received_kes", "mpesa_variance_kes"]],
hide_index=True, use_container_width=True)
What makes this "interactive" in a useful sense is not animation but control: managers choose the period and branches, every tile compares against the previous equivalent period, and the exceptions table turns an abstract variance into a list of days finance can investigate.
Deploying it safely
- Run the app in a container on a small VM or platform service, close to the reporting database.
- Put it behind single sign-on or a VPN; Streamlit does not provide enterprise authentication on its own.
- Store
REPORTING_DB_URLin a secrets manager or environment variables, never in the repository. - Use TLS end to end.
- Monitor the ingestion service: alert if no M-Pesa callbacks have arrived for an unusually long period during trading hours, which usually means an endpoint or certificate problem.
If you prefer an off-the-shelf BI tool, the same kpi_daily view can be connected to Power BI, Metabase or Looker Studio. See Best Business Intelligence Tools for Small Businesses for options.
Data protection and compliance
- Minimise personal data. The dashboard needs counts of payers, not their phone numbers. Hash MSISDNs with a secret salt at ingestion and restrict raw data to the finance system of record.
- Access control. Branch managers may only need their own branch. Implement row-level filtering based on the signed-in user.
- Retention. Define how long raw transaction data stays in the reporting database.
- Tax alignment. If your revenue KPI should match figures transmitted to KRA through eTIMS, define it using the same VAT treatment and invoice status so the numbers reconcile.
Common mistakes
- Timezone drift. Grouping UTC timestamps by date shifts sales after 21:00 East Africa Time into the next day. Always convert to Africa/Nairobi before truncating to a date.
- Floating-point money. Use
numericin the database; convert to float only for display. - Ignoring reversals. M-Pesa reversals and POS refunds must be excluded or netted, or revenue will be overstated.
- Too many charts. If a chart does not lead to an action, remove it.
- No owner for data quality. Assign someone to investigate reconciliation exceptions every day.
- Querying production directly. It slows down checkout at the worst possible moment.
FAQ
What tools do I need to build a business dashboard?
At minimum: a database for clean, modelled data (PostgreSQL is a solid default), a process to load data into it, and a presentation layer such as Streamlit, Power BI, Metabase or Looker Studio.
How do I get M-Pesa data into a dashboard?
Register a C2B callback URL with Safaricom's Daraja API to receive payment confirmations into your database, and import statements periodically to reconcile any missed callbacks.
How many KPIs should a dashboard have?
Five to seven headline KPIs is a practical maximum for one view. Provide drill-downs for detail rather than adding more tiles.
Should a dashboard be real time?
Only if decisions are made in real time. Most SME decisions are daily or weekly; hourly refresh with caching is usually sufficient and far cheaper.
How TechBytes can help
We build end-to-end analytics pipelines for East African businesses: Daraja integrations, reporting databases, reconciled KPI models and dashboards in Streamlit, Power BI or Metabase. We also handle hosting, access control and data protection design so the dashboard is secure from day one. See our software development services or request a quote.

