Module 4 Β· Lecture 14

Grafana Fundamentals: Connecting Data to Dashboards

Install Β· Import transactions into MySQL Β· Build a transaction-risk dashboard

⏱ 90 minutes πŸ“ Prerequisites: Lectures 10–11 (transaction data) πŸ”§ Lab: Docker + Grafana setup

Contents

  1. Learning Objectives
  2. Session Timeline
  3. What Is Grafana?
  4. The Grafana Mental Model
  5. Setup & Connection
  6. Import the Existing Transactions
  7. Hands-On Lab β€” Transaction Risk Dashboard
  8. Panel Types Overview
  9. Key Takeaways

Learning Objectives

Session Timeline

TimeSegmentActivity
0–10 minRecapFrom Kafka storage to business decisions
10–20 minWhat Is Grafana?Architecture, users, and business value
20–30 minGrafana Mental ModelData sources, queries, panels, dashboards
30–45 minSetup & ConnectionRun MySQL and Grafana with Docker
45–55 minExisting DatasetImport the Lecture 10 transactions CSV
50–80 minDashboard LabBuild a Stat, Bar Chart, and Table panel
80–88 minInterpretationRead the dashboard and recommend an action
88–90 minWrap-UpSave the dashboard and preview Lecture 15

Section 1: What Is Grafana?

The Problem It Solves

In Modules 2 and 3, you built the full backend: Kafka producers, consumers, MongoDB storage, alert routing, and windowing. All that work produces data β€” but the data lives in a database only engineers can query. Grafana closes this gap. It turns database queries into visual panels that refresh automatically, putting your streaming data in front of the people who need to act on it.

What It IsWhat It Isn't
A dashboard and visualisation platformA database
A query builder (UI on top of your data)A streaming system
An alerting layer with notification routingA replacement for MongoDB/Kafka
Open source + free for self-hosted useAn analytics/BI tool (that's Metabase, Tableau)

Who Uses Grafana

2014 β€” Created by Torkel Odegaard as a fork of Kibana
2021 β€” Grafana Labs valued at $3 billion
2024 β€” ~20 million users, 200,000+ organisations
      Default monitoring dashboard at:
      Netflix, PayPal, Booking.com, Zepto, Swiggy, Paytm, HDFC Securities

Career context: When you walk into a data-forward company's operations centre and see a wall of live charts, there is a 70%+ chance you are looking at Grafana. Understanding this tool positions you to have meaningful conversations about data infrastructure β€” as a manager, analyst, or product leader.

Section 2: The Grafana Mental Model

Four Building Blocks

  1. Data Source β€” A connection to a database. This lab uses MySQL because Grafana supports it without an Enterprise plugin.
  2. Query β€” The question you're asking of the data source. This lab uses SQL.
  3. Panel β€” One visual unit: one chart, one number, one table. Each panel has exactly one query and one visualisation type.
  4. Dashboard β€” A collection of panels on a grid. Has a time range selector and auto-refresh interval.

Time as a First-Class Citizen

Unlike static BI tools, Grafana treats time as the primary dimension. Every dashboard has a time range (last 5 min, last 1 hour, custom). This makes it ideal for streaming data β€” you can zoom into the exact window when an alert fired.

Section 3: Setup & Connection

Why MySQL? Grafana's MongoDB datasource requires an Enterprise entitlement that is not available for this course. MySQL is supported directly by Grafana, so every student can complete the lab without a paid plugin.

Run MySQL and Grafana with Docker

# Create one network so Grafana can reach MySQL by container name
docker network create sda-analytics

docker run -d \
  --name sda-mysql \
  --network sda-analytics \
  -e MYSQL_ROOT_PASSWORD=admin \
  -p 3306:3306 \
  mysql:8.4 \
  --local-infile=1

docker run -d \
  --name grafana \
  --network sda-analytics \
  -p 3000:3000 \
  -e GF_SECURITY_ADMIN_PASSWORD=admin \
  grafana/grafana:latest

# Open http://localhost:3000 and log in with admin / admin

Add the Built-In MySQL Data Source

1

Left sidebar β†’ Connections β†’ Data Sources β†’ Add data source

2

Search "MySQL" β†’ select the built-in datasource

3

Host: sda-mysql:3306 | Database: sda_course
User: grafana | Password: grafana | TLS/SSL mode: disabled for this local lab

4

Keep this browser tab open. Create the database and read-only user below, then return and click "Save & Test".

Section 4: Import the Existing Transactions

Reuse the transactions.csv generated in Lecture 10. This is the same dataset used in the Kafka fraud exercise; MySQL is only an additional analytics destination for Grafana.

Live-stream alternative: Instead of importing the CSV, run Lecture 10's consumer_store_mysql.py while transaction_producer.py is publishing. The consumer creates and continuously populates the same sda_course.transactions table used below. Its upsert makes Kafka replays safe.

Fields Used Today

FieldExampleBusiness Meaning
transaction_idTXN-00847Unique transaction reference
amount4500.00Transaction value imported as a decimal
cityMumbaiLocation where the transaction occurred
merchantAmazonMerchant receiving the payment
timestamp2025-08-01 10:00:00Business event time imported as DATETIME
is_fraudtrueClassroom fraud label

Create the Table and Import the CSV

Run these commands from the folder containing transactions.csv:

docker cp transactions.csv sda-mysql:/var/lib/mysql-files/transactions.csv
docker exec -it sda-mysql mysql -uroot -padmin

Then run this SQL in the MySQL prompt:

CREATE DATABASE IF NOT EXISTS sda_course;
USE sda_course;

DROP TABLE IF EXISTS transactions;
CREATE TABLE transactions (
  transaction_id VARCHAR(20) PRIMARY KEY,
  user_id VARCHAR(20),
  user_name VARCHAR(100),
  card_last4 VARCHAR(4),
  amount DECIMAL(12,2),
  merchant VARCHAR(100),
  city VARCHAR(50),
  country VARCHAR(50),
  lat DECIMAL(9,4),
  lon DECIMAL(9,4),
  `timestamp` DATETIME,
  is_fraud VARCHAR(5),
  ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

LOAD DATA INFILE '/var/lib/mysql-files/transactions.csv'
INTO TABLE transactions
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(transaction_id,user_id,user_name,card_last4,amount,merchant,
 city,country,lat,lon,`timestamp`,is_fraud);

CREATE USER IF NOT EXISTS 'grafana'@'%' IDENTIFIED BY 'grafana';
GRANT SELECT ON sda_course.* TO 'grafana'@'%';
FLUSH PRIVILEGES;

SELECT COUNT(*) AS total_transactions,
       SUM(is_fraud = 'true') AS flagged_transactions
FROM transactions;

Checkpoint: The deterministic Lecture 10 generator produces 2,003 transactions with 76 flagged records. Return to Grafana and click Save & Test.

Section 5: Hands-On Lab β€” Transaction Risk Dashboard

Scenario: You manage fraud operations for a digital bank. Your team needs one screen that answers three questions: What percentage of transactions are flagged? Which cities carry the most transaction value? Which individual transactions require review?

Panel A β€” Fraud Rate

Stat visualisation for an immediate risk KPI.

Panel B β€” Value by City

Bar Chart to compare geographic exposure.

Panel C β€” Review Queue

Table listing transactions requiring attention.

Step 1 β€” Create and Name the Dashboard

  1. Go to Dashboards β†’ New β†’ New Dashboard.
  2. Select Add visualisation, then choose the MySQL data source.
  3. Click Save dashboard and name it Transaction Risk Overview β€” Lecture 14.
  4. Because this is a fixed historical dataset, set a custom dashboard time range of 1 August–31 August 2025.

Step 2 β€” Panel A: Flagged Transaction Rate

This panel answers: β€œWhat percentage of transactions are labelled as fraud?”

SELECT
  100.0 * SUM(is_fraud = 'true') / COUNT(*) AS value
FROM transactions;
  1. Choose the Stat visualisation.
  2. Set the title to Flagged Transaction Rate.
  3. Set the unit to Percent (0–100) and decimals to 1.
  4. Add thresholds: green below 3%, amber from 3%, red from 5%.
  5. Click Apply. The generated dataset should display 3.8% in amber.

Step 3 β€” Panel B: Transaction Value by City

This panel answers: β€œWhere is the bank's transaction value concentrated?”

SELECT city, SUM(amount) AS value
FROM transactions
GROUP BY city
ORDER BY value DESC;
  1. Add a visualisation and choose Bar Chart.
  2. Set the title to Transaction Value by City.
  3. Use city as the category and value as the numeric field.
  4. Set the value unit to Indian Rupee and orientation to horizontal.
  5. Click Apply.

Step 4 β€” Panel C: Flagged Transactions for Review

This panel answers: β€œWhich transactions should an analyst inspect first?”

SELECT
  transaction_id,
  `timestamp`,
  user_name,
  merchant,
  city,
  amount
FROM transactions
WHERE is_fraud = 'true'
ORDER BY amount DESC
LIMIT 20;
  1. Add another visualisation and choose Table.
  2. Set the title to Flagged Transactions β€” Review Queue.
  3. Organize columns as Transaction ID, Timestamp, Customer, Merchant, City, Amount.
  4. Set Amount to Indian Rupee and sort it descending.
  5. Click Apply.

Step 5 β€” Arrange and Refresh

  1. Place the Fraud Rate Stat panel at the top left.
  2. Place the city Bar Chart beside it and give it more width.
  3. Place the Review Queue Table across the full width below.
  4. Set dashboard refresh to 30 seconds and save.

Important: Refreshing reruns the queries; it does not generate or re-import transactions. This lab uses a fixed MySQL copy of the Lecture 10 dataset.

Step 6 β€” Read the Dashboard Like a Manager

  1. Observe: Read the fraud-rate KPI before looking at individual rows.
  2. Prioritise: Use the review queue to identify the highest-value flagged transactions.
  3. Contextualise: Compare city exposure before treating a high count as unusual.
  4. Decide: Recommend investigation or monitoring; the label is a signal, not proof of fraud.

Success checklist: Your dashboard has three titled panels, displays a fraud-rate percentage, compares transaction value by city, lists the 20 highest-value flagged transactions, and supports one clear management recommendation.

Section 6: Panel Types Reference

Panel TypeBest ForExample Use
Time SeriesTrends over timeTransaction count or value per hour
StatSingle important numberFraud rate or total transaction value
Bar GaugeProgress / comparisonFlagged transactions by merchant
Bar ChartCategorical comparisonTransaction value by city
TableRaw data / detail viewFlagged transactions requiring review
GaugeSingle value with thresholdsRisk score: green/amber/red

Key Takeaways

βœ“ Key Takeaways β€” Lecture 14

  1. Grafana is the visual layer β€” it sits on top of databases, not inside them
  2. Four building blocks: Data Source β†’ Query β†’ Panel β†’ Dashboard
  3. Time is central β€” dashboards have a time range and auto-refresh, making them live
  4. MySQL provides a free built-in Grafana datasource for the course transaction dataset
  5. A useful dashboard begins with business questions, not chart types
  6. Stat, Bar Chart, and Table panels answer KPI, comparison, and detail questions
  7. Auto-refresh reruns queries; the source pipeline is what creates new data

Preview β€” Lecture 15: Building Live Streaming Dashboards

Extend today's transaction dashboard with more panels, reusable variables, and Assignment 3 design guidance. Keep the MySQL and Grafana containers running.