We are going to design a backlog health monitor that measures cycle time for different types of tasks: UI, backend, and ML.
Cycle time is the time taken from when a task starts (or is picked up) until it is completed.
We assume that we have a way to track tasks (like in an issue tracker such as Jira, GitHub Issues, etc.) and that each task has:
Type (UI, backend, ML)
Start date (or when it was moved to "In Progress")
End date (or when it was moved to "Done")
However, note that sometimes tasks might not have a clear start date (if they were never in an "In Progress" state) or might have multiple start/stop events.
For simplicity, we'll assume:
Each task has a unique ID.
We have a way to get the start and end timestamps for each task.
Steps for the monitor:
Data Collection: We need to fetch the tasks from the issue tracking system. We might use an API to get the tasks with their type, start, and end dates.
Filtering: We might want to filter tasks by:
Status: only completed tasks (with both start and end dates).
Time frame: only tasks completed in the last N days (e.g., last 90 days).
Exclude certain tasks (like by label, project, etc.)
Calculation: For each task type, calculate the cycle time (end - start) in days (or hours, but usually days for software tasks).
Aggregation: We can calculate:
Average cycle time per type.
Median cycle time per type (to avoid skew from outliers).
Percentiles (e.g., 85th, 95th) to understand the tail.
Trend over time (e.g., by week or month).
Visualization: We can display the results in a dashboard with:
A table or bar chart for average/median cycle times per type.
A control chart (like a run chart) to show cycle time over time for each type (or overall).
A histogram for cycle times for each type.
Alerts: We might set thresholds and alert if the cycle time for a type exceeds a certain limit for a given period.
However, note that the requirement is to "architect" a backlog health monitor, so we are going to design the system.
Let's break down the components:
A. Data Source: Issue tracking system (Jira, GitHub, etc.). We'll need to connect to their API.
B. Data Storage: We might not need to store the data if we can compute on the fly, but for historical trend we might want to store snapshots.
Alternatively, we can store the raw task data and then compute at query time. But if we want to track trends, we need to store at least the cycle time per task and the completion date.
C. Processing: We can either:
- Pull the data on demand (when the dashboard is loaded) and calculate then, or
- Have a scheduled job that fetches new tasks periodically and updates the aggregated metrics and stores them in a database for quick retrieval.
D. Dashboard: A web-based dashboard that shows the metrics and charts.
E. Alerting: A component that checks the metrics against thresholds and sends alerts (email, Slack, etc.).
Let's consider the following architecture:
Option 1: Real-time (or near real-time) dashboard.
Steps:
1. A scheduled job (e.g., every hour) runs:
- Fetches the tasks from the issue tracker that were updated (or completed) since the last run.
- For each new completed task, calculates the cycle time and stores it in a database (with task type, cycle time, completion date, etc.)
- Also, we can update the aggregated metrics (like daily average per type) and store those in a separate table for quick retrieval.
code
2. The dashboard queries the aggregated metrics (or the raw data and calculates on the fly) and displays.
Advantages:
- Fast dashboard because we pre-compute.
- We can store historical data for trends.
Disadvantages:
- We have to manage a database and scheduled jobs.
Option 2: On-demand computation.
Steps:
1. When the dashboard is loaded, it calls an API that:
- Fetches the tasks from the issue tracker (with a filter for completed tasks in the last, say, 90 days).
- Calculates the cycle times and aggregates in memory.
- Returns the results.
Advantages:
- No need for a separate database or scheduled job.
- Always up-to-date.
Disadvantages:
- Slower because we fetch and compute every time.
- Issue tracker API might have rate limits.
Given that we want to monitor trends over time, we need to store historical data. So we go with Option 1.
Proposed Architecture:
Data Fetcher (Scheduled Job):
Runs every hour (or day, depending on the volume and need for freshness).
Uses the issue tracker's API to get tasks that were completed in the last day (or since last run).
For each task, we need:
task_id, task_type, start_date, end_date, cycle_time (calculated as end_date - start_date in days)
Stores each task's cycle time in a table task_cycle_times with columns:
id (auto), task_id (string, unique per issue tracker), task_type (enum: 'UI', 'backend', 'ML'),
cycle_time_days (float), completed_date (date), fetched_at (timestamp)
Also, we can pre-compute daily aggregates (per type) and store in daily_metrics:
date (date), task_type, avg_cycle_time, median_cycle_time, p85_cycle_time, p95_cycle_time, task_count
How to compute daily aggregates? We can compute for each day (the completion date) and for each task type.
Database: We can use a relational database (PostgreSQL) or a time-series database (if we want to focus on time series).
Since we have two main tables (raw tasks and daily aggregates) and we might want to join by date and type, a relational database is fine.
Dashboard API:
An API server (e.g., in Python with Flask/Django, or Node.js) that serves the dashboard.
It will have endpoints to get:
a. The latest daily metrics for each task type (or for a given date range).
b. The raw task cycle times for a given date range (if we want to show a histogram or control chart without pre-aggregation).
c. Trend data (by week or month) if we want to show a line chart of average cycle time over time.
Dashboard Frontend:
A web page (using React, Vue, or plain HTML/JS) that calls the API and displays:
A table with current (last 7 days, or last 30 days) average and median cycle times per type.
A line chart for the trend of average cycle time over the last 90 days (by week) for each type.
A control chart (like a run chart) for each type (or overall) showing cycle time per task (or per day) with upper and lower control limits.
Alerting:
We can have a separate scheduled job that runs (say, every day) and checks the latest metrics.
For each task type, if the average (or median) cycle time for the last 7 days exceeds a threshold (or if the 95th percentile exceeds a threshold), send an alert.
Configuration:
We need to store configuration such as:
Issue tracker API credentials.
Implementation Steps:
Step 1: Set up the database.
Step 2: Write the data fetcher script.
Step 3: Set up the API server.
Step 4: Build the dashboard frontend.
Step 5: Set up the alerting job.
Step 6: Deploy and monitor the system itself.
Let's sketch the database schema:
Table: task_cycle_times
- id (bigserial, primary key)
- task_id (varchar, not null) [the issue tracker's task ID, e.g., "PROJ-123"]
- task_type (varchar, not null) [we can use an enum type if we want, but for simplicity string]
- cycle_time_days (numeric, not null) [float, can be fractional days]
- completed_date (date, not null) [the date when the task was completed (from the end_date)]
- fetched_at (timestamp, not null) [when we fetched this task]
code
Indexes:
on task_id (to avoid duplicates, we might set task_id as unique if we only fetch each task once? But if a task is updated, we might refetch. So maybe we allow duplicates and then when aggregating we take the latest fetched_at? Alternatively, we can use an upsert: if task_id already exists, update the record if the fetched_at is newer? But note: the cycle time might change if the start or end date changed. So we might want to update the record if the task was updated in the issue tracker.)
Alternatively, we can store every fetch and then when we compute daily aggregates, we use the latest record for each task_id (by fetched_at). But that complicates.
Another idea: when we fetch, we get the current state of the task (start and end). If we already have a record for that task_id and the end_date is the same, then we don't update? But if the start_date changed, we update.
However, for simplicity, let's assume that once a task is completed, its start and end dates don't change. Then we can set task_id as unique and do an upsert (insert if not exists, update if exists and the fetched_at is newer). But if we update, we must also update the daily aggregates? That's more complex.
Alternatively, we can have a separate table for the current state of each task (the latest we fetched) and then when we compute daily aggregates, we use that table? But then we lose history of changes.
Given that cycle time is a post-facto metric and we are interested in the cycle time at completion, it's unlikely to change. So let's assume we only fetch completed tasks and once we fetch a completed task, we don't refetch it unless it's reopened? But then if it's reopened and then completed again, it's a new cycle? That's a different scenario.
Let's stick to: each time we run the fetcher, we get all tasks that were completed in the last day (or since last run). We then store each task with a unique constraint on (task_id, completed_date). But note: a task might be completed, then reopened, then completed again? Then we would have two records with the same task_id but different completed_date? That's acceptable because they are two different cycles.
So we can have a unique constraint on (task_id, completed_date) to avoid duplicates for the same cycle.
Table: daily_metrics
- id (bigserial, primary key)
- metric_date (date, not null) [the date for which we are storing the metrics (the completion date of the tasks)]
- task_type (varchar, not null)
- avg_cycle_time (numeric)
- median_cycle_time (numeric)
- p85_cycle_time (numeric)
- p95_cycle_time (numeric)
- task_count (integer)
code
Unique constraint on (metric_date, task_type)
How to compute daily_metrics?
code
For a given date D and task type T, we look at all tasks of type T that have completed_date = D and that we have fetched (and are the latest fetch for that task?).
But note: we might have multiple records for the same task on the same day? If a task was completed and we fetched it on two different days (because it was updated) then we have two records. We want the latest record? Or we want to avoid duplicates by task_id and completed_date? Let's say we have a unique constraint on (task_id, completed_date) in task_cycle_times, then we only have one record per task per completion.
Then for a given day D and type T, we take all task_cycle_times with completed_date = D and task_type = T, and calculate the statistics.
We can compute these statistics when we insert a new task for that day? But then we have to update the daily_metrics for that day every time we add a new task for that day? Alternatively, we can recompute the entire day's metrics every time we add a task? That might be heavy if we have many tasks per day.
Alternatively, we can have a separate job that runs after the fetcher and recomputes the daily_metrics for the days that were updated.
But for simplicity, let's do:
When the fetcher runs and fetches tasks for a set of completed_dates (say, yesterday and maybe a few days before if we are catching up), then for each of those dates and for each task type, we recompute the daily_metrics from scratch (by querying all tasks of that type and completed_date). This is acceptable if we don't have too many tasks per day (thousands) and we do it only for the days that changed.
Steps in the fetcher:
For each task fetched (with completed_date in the last day, or since last run):
Insert or update (if exists) the task_cycle_times record (using task_id and completed_date as unique key).
Then, for each unique completed_date that we touched, and for each task_type that we have tasks for on that date, recompute the daily_metrics for that (date, type).
We can do:
For each date in the set of completed_dates we fetched:
For each task_type in (UI, backend, ML):
SELECT cycle_time_days FROM task_cycle_times
WHERE completed_date = :date AND task_type = :type
Then compute:
avg, median, p85, p95, count
Then upsert into daily_metrics (metric_date, task_type, ...) with these values.
This way, the daily_metrics table is always up-to-date for the days we fetched.
Then the dashboard API can just query the daily_metrics table for the last N days and display.
For the control chart (showing individual tasks over time) we might want to query the task_cycle_times table for a given date range and type, and then plot the cycle times (with the task_id or just the value) over time (completed_date). We can also compute the average and standard deviation for the entire period (or for each week) to draw control limits.
Alternatively, we can pre-compute control limits per week? But let's keep it simple and do on the frontend or in the API.
The API can have:
code
GET /api/metrics/daily?start_date=...&end_date=... [returns daily_metrics for the date range]
GET /api/tasks?start_date=...&end_date=...&task_type=... [returns list of tasks (cycle_time_days, completed_date) for the given criteria]
Then the frontend can compute the control chart from the tasks.
Alternatively, we can have an endpoint that returns the tasks and also the control limits (average and standard deviation) for the selected period and type.
Then the frontend can plot the tasks as a scatter plot (or run chart) with horizontal lines for the control limits.
For the trend line (average cycle time over time by week), we can use the daily_metrics table and group by week.
Alternatively, we can have a separate table for weekly metrics? But we can compute on the fly from daily_metrics.
We can have:
code
GET /api/trend?task_type=UI&period=weekly&start_date=...&end_date=...
Returns an array of { period: "2024-W01", avg_cycle_time: 4.5, median_cycle_time: 4.2, ... }
But note: the daily_metrics table already has average and median per day. We can aggregate by week (or month) in the query.
Let's keep the API simple and let the frontend or the API server aggregate from daily_metrics.
Alternatively, we can have the API do the aggregation:
code
Step 4: Alerting.
code
We can have a job that runs every day and checks the summary for the last 7 days (or 3 days) for each task type.
If the average (or median) cycle time for a type is above a threshold (configurable) for the last 7 days, then send an alert.
We can also check if the trend is increasing (using a linear regression on the last few weeks?).
But for simplicity, let's just check the absolute value.
We can store the thresholds in a config file or database.
Example:
thresholds = {
'UI': {'avg': 5, 'median': 4},
'backend': {'avg': 7, 'median': 6},
'ML': {'avg': 10, 'median': 9}
}
Then for each type, if the current average (for the last 7 days) is above the threshold, alert.
We can also have a threshold for the 95th percentile.
Step 5: Deployment.
code
We can run the fetcher as a cron job (or a scheduled task in the OS, or a Kubernetes cron job).
The API server can be a web service (like Flask) running on a server.
The frontend can be static files served by the same server or a separate one.
We need to secure the API (maybe with an API key) if it's internal.
Let's summarize:
code
Components:
1. Database (PostgreSQL) with one table: task_cycle_times.
2. Fetcher script (in Python, using the issue tracker's API) that runs every hour.
3. API server (Python Flask) that serves the dashboard data.
4. Dashboard frontend (HTML/JS) that calls the API and displays charts (using a charting library like Chart.js).
5. Alerting script (can be part of the fetcher or a separate cron job) that checks thresholds and sends alerts.
Let's write the SQL for the task_cycle_times table:
code
CREATE TABLE task_cycle_times (
id BIGSERIAL PRIMARY KEY,
task_id VARCHAR(255) NOT NULL,
task_type VARCHAR(50) NOT NULL,
cycle_time_days NUMERIC NOT NULL,
completed_date DATE NOT NULL,
fetched_at TIMESTAMP NOT NULL,
UNIQUE (task_id, completed_date)
);
Indexes:
CREATE INDEX idx_task_cycle_times_completed_date ON task_cycle_times(completed_date);
CREATE INDEX idx_task_cycle_times_task_type ON task_cycle_times(task_type);
The fetcher script:
code
Step 6: Alerting.
code
We can have a separate script that runs once a day (say, at 8 AM) and:
- For each task_type, query the average and median cycle time for the last 7 days (from task_cycle_times).
- Compare with the thresholds (stored in a config file or environment variables).
- If exceeded, send an alert (via email, Slack, etc.).
We can also check the trend (e.g., if the average for the last 7 days is higher than the average for the previous 7 days by a certain percentage).
Step 7: Dashboard.
code
We'll build a simple HTML page with:
- A dropdown to select the task type (or show all types in separate charts).
- A chart for the trend (line chart with weeks on x-axis and average cycle time on y-axis, one line per task type).
- A control chart for the selected task type (scatter plot of cycle time vs. completed_date, with horizontal lines for average and control limits).
We can use Chart.js for the line chart and scatter plot.
We'll have:
<select id="taskType">
<option value="all">All</option>
<option value="UI">UI</option>
<option value="backend">Backend</option>
<option value="ML">ML</option>
</select>
<canvas id="trendChart"></canvas>
<canvas id="controlChart"></canvas>
Then we use JavaScript to call the API and draw the charts.
This is a high-level design. We'll need to adjust based on the actual issue tracker's capabilities.
Let's note the challenges:
code
- Getting the start date: this is the hardest part because different issue trackers and different teams have different processes.
- Handling tasks that are reopened: we might want to reset the start date when reopened? Or consider only the last cycle? We are storing by completed_date, so if a task is completed, then reopened and completed again, we have two records with the same task_id but different completed_date. That's acceptable.
We assume that the issue tracker provides a way to get the start date (when the task was first moved to an in-progress state). If not, we might use the creation date as a proxy, but that would include time in backlog before work started.
We might want to exclude tasks that were never in an "In Progress" state? Or use the creation date if no in-progress date? We need a rule.
Let's define:
code
start_date =
if there is a transition to "In Progress" (or similar), then the first such transition date.
else, the creation date.
But note: some tasks might be created and then immediately started? Then the creation date is close to the start date.
This is a heuristic.
Finally, we must consider time zones. The issue tracker might store dates in UTC, and we want to compute cycle time in working days? Or calendar days? Usually cycle time is calendar days (including weekends) because we want to measure the elapsed time. But sometimes teams use working days. We need to decide.
Let's use calendar days for simplicity.
So cycle_time_days = (completed_date - start_date) in days (as a float, so if start is 2024-01-01 10:00 and completed is 2024-01-02 14:00, then it's 1.17 days).
But if we only have dates (without time) then we can do:
This is a comprehensive design. We can now proceed to implementation, but note that the question was to architect, so we stop at design.
However, we can provide a sample implementation for one component (like the fetcher for Jira) as an example.
But since the question is about architecture, we have provided the design.
Let me know if you have any questions or need more details on a specific part.
I'll design a comprehensive Backlog Health Monitor that tracks cycle time across UI, backend, and ML workstreams. Here's a complete architecture:
-- Tasks with cycle time calculations
CREATE TABLE task_cycle_times (
task_id VARCHAR PRIMARY KEY,
issue_key VARCHAR NOT NULL,
task_type VARCHAR(20) CHECK (task_type IN ('ui', 'backend', 'ml', 'other')),
project_key VARCHAR NOT NULL,
status VARCHAR(50),
-- Timestamps
created_at TIMESTAMP NOT NULL,
started_at TIMESTAMP, -- First "In Progress" transition
completed_at TIMESTAMP,
-- Calculated metrics
cycle_time_days NUMERIC,
cycle_time_hours NUMERIC,
waiting_time_days NUMERIC, -- Time in "To Do"/"Backlog"
active_time_days NUMERIC, -- Time in "In Progress"
-- Metadata
priority VARCHAR(20),
story_points INTEGER,
assignee VARCHAR(100),
sprint_id VARCHAR(50),
-- Derived flags
is_ml_task BOOLEAN GENERATED ALWAYS AS (
task_type = 'ml' OR
labels @> '["ml"]'::jsonb OR
summary ILIKE '%machine learning%'
) STORED,
time_bucket TIMESTAMP GENERATED ALWAYS AS (
date_trunc('week', COALESCE(completed_at, NOW()))
) STORED
);
-- Aggregate metrics for daily/weekly reporting
CREATE TABLE cycle_time_aggregates (
time_bucket TIMESTAMP NOT NULL,
task_type VARCHAR(20) NOT NULL,
project_key VARCHAR NOT NULL,
-- Metrics
avg_cycle_time NUMERIC,
median_cycle_time NUMERIC,
p85_cycle_time NUMERIC,
p95_cycle_time NUMERIC,
task_count INTEGER,
-- Throughput metrics
completed_count INTEGER,
throughput INTEGER, -- Completed per week
-- Quality metrics
percent_within_sla NUMERIC, -- % within target cycle time
PRIMARY KEY (time_bucket, task_type, project_key)
);
2. Data Pipeline (Python-based ETL)
python
# src/pipeline/extractors/base.py
class IssueExtractor(ABC):
@abstractmethod
def fetch_tasks(self, since: datetime) -> List[Task]:
"""Fetch tasks changed since timestamp"""
pass
@abstractmethod
def get_transitions(self, issue_key: str) -> List[StatusTransition]:
"""Get complete status change history"""
# src/pipeline/transform/cycle_time_calculator.py
class CycleTimeCalculator:
def __init__(self, config: Config):
self.status_mapping = config.status_mapping # e.g., {'To Do': 'backlog', 'In Progress': 'active'}
self.task_type_classifier = TaskTypeClassifier()
def calculate_metrics(self, task: Task) -> TaskMetrics:
transitions = self.get_sorted_transitions(task)
# Find key timestamps
start_time = self._find_first_progress(transitions)
completion_time = self._find_completion(transitions)
if not start_time or not completion_time:
return None
# Calculate time segments
cycle_time = (completion_time - start_time).total_seconds() / 86400
# Classify task type
task_type = self.task_type_classifier.classify(task)
return TaskMetrics(
task_id=task.id,
task_type=task_type,
cycle_time_days=cycle_time,
started_at=start_time,
completed_at=completion_time,
status_sequence=[t.status for t in transitions]
)
# src/pipeline/load/warehouse.py
class MetricsLoader:
def upsert_task_metrics(self, metrics: List[TaskMetrics]):
"""Upsert using ON CONFLICT for idempotency"""
query = """
INSERT INTO task_cycle_times
(task_id, task_type, cycle_time_days, started_at, completed_at, ...)
VALUES (%s, %s, %s, %s, %s, ...)
ON CONFLICT (task_id)
DO UPDATE SET
cycle_time_days = EXCLUDED.cycle_time_days,
completed_at = EXCLUDED.completed_at,
updated_at = NOW();
"""
3. Metrics Calculation & Aggregation
sql
-- materialized view refreshed every hour
CREATE MATERIALIZED VIEW mv_weekly_cycle_times
WITH (timescaledb.continuous) AS
SELECT
time_bucket('1 week', completed_at) AS week,
task_type,
project_key,
-- Core metrics
AVG(cycle_time_days) AS avg_cycle_time,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY cycle_time_days) AS median,
PERCENTILE_CONT(0.85) WITHIN GROUP (ORDER BY cycle_time_days) AS p85,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY cycle_time_days) AS p95,
COUNT(*) AS task_count,
-- Throughput
COUNT(*) FILTER (WHERE completed_at >= NOW() - INTERVAL '7 days') AS weekly_throughput,
-- SLA compliance (example: UI < 3 days, backend < 5 days, ML < 10 days)
AVG(CASE
WHEN task_type = 'ui' AND cycle_time_days <= 3 THEN 1
WHEN task_type = 'backend' AND cycle_time_days <= 5 THEN 1
WHEN task_type = 'ml' AND cycle_time_days <= 10 THEN 1
ELSE 0
END) * 100 AS sla_compliance_pct
FROM task_cycle_times
WHERE completed_at IS NOT NULL
GROUP BY week, task_type, project_key;
-- Refresh policy (every 4 hours)
SELECT add_continuous_aggregate_policy('mv_weekly_cycle_times',
start_offset => INTERVAL '4 weeks',
end_offset => INTERVAL '1 hour',
schedule_interval => INTERVAL '4 hours');
4. Dashboard Components
A. Executive Summary Panel
Overall Health Score: Weighted average of SLA compliance
-- Generate control chart data for specific workstream
SELECT
completed_at,
cycle_time_days,
AVG(cycle_time_days) OVER () AS mean,
STDDEV(cycle_time_days) OVER () AS std_dev,
(AVG(cycle_time_days) OVER () + 2 * STDDEV(cycle_time_days) OVER ()) AS ucl,
(AVG(cycle_time_days) OVER () - 2 * STDDEV(cycle_time_days) OVER ()) AS lcl
FROM task_cycle_times
WHERE task_type = 'ml'
AND completed_at >= NOW() - INTERVAL '90 days';
D. Cumulative Flow Diagram (CFD)
sql
SELECT
date_trunc('day', status_changed_at) AS day,
status,
COUNT(*) AS count
FROM status_transitions
GROUP BY day, status
ORDER BY day;
5. Alerting System
python
# src/alerts/rules.py
class CycleTimeAlertRule:
def __init__(self, task_type: str, threshold_days: float,
window_days: int = 7, deviation_pct: float = 0.2):
self.task_type = task_type
self.threshold = threshold_days
self.window = window_days
self.deviation = deviation_pct
def check(self, db: Connection) -> List[Alert]:
query = """
SELECT
task_type,
AVG(cycle_time_days) as avg_cycle,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY cycle_time_days) as median
FROM task_cycle_times
WHERE completed_at >= NOW() - INTERVAL '{window} days'
AND task_type = '{task_type}'
GROUP BY task_type
HAVING AVG(cycle_time_days) > {threshold}
OR PERCENTILE_CONT(0.5) > {threshold}
""".format(window=self.window, task_type=self.task_type,
threshold=self.threshold)
result = db.execute(query)
alerts = []
for row in result:
if row['avg_cycle'] > self.threshold * (1 + self.deviation):
alerts.append(Alert(
severity='critical',
message=f"{self.task_type} cycle time {row['avg_cycle']:.1f}d exceeds {self.threshold}d",
metric='cycle_time',
current_value=row['avg_cycle'],
threshold=self.threshold
))
return alerts
# Alert channels: Slack, Email, PagerDuty integration
def validate_task(task: Task) -> bool:
"""Filter out noisy/invalid data"""
if not task.started_at or not task.completed_at:
return False
if task.cycle_time_days <= 0:
return False
if task.cycle_time_days > 365: # Cap at 1 year
return False
if task.story_points is None or task.story_points < 1:
return False
return True
Classification Strategy
Manual labeling: Track type field in issue tracker
Label-based: Use ml, frontend, backend labels
Regex patterns: Component in path (src/ui/, src/api/)
ML model: Train classifier on historical labels (optional)
Performance Optimizations
Partition task_cycle_times by completed_at (monthly)
Create BRIN indexes on time columns
Use continuous aggregates for common queries
Cache dashboard results (Redis, 5-min TTL)
9. Sample API Endpoints
python
# FastAPI endpoints
@app.get("/api/v1/health/summary")
async def get_health_summary(days: int = 30):
"""Executive summary for last N days"""
return await db.fetch("""
SELECT
task_type,
AVG(cycle_time_days) as avg_cycle,
PERCENTILE_CONT(0.5) as median,
COUNT(*) as count,
AVG(CASE WHEN cycle_time_days <= target THEN 1 ELSE 0 END) as sla_compliance
FROM mv_weekly_cycle_times
WHERE time_bucket >= NOW() - INTERVAL '{days} days'
GROUP BY task_type
""")
@app.get("/api/v1/health/control-chart/{task_type}")
async def get_control_chart(task_type: str, weeks: int = 12):
"""Data for Shewhart control chart"""
return await db.fetch("""
SELECT
completed_at::date as date,
cycle_time_days,
AVG(cycle_time_days) OVER () as mean,
STDDEV(cycle_time_days) OVER () as stddev
FROM task_cycle_times
WHERE task_type = $1
AND completed_at >= NOW() - INTERVAL '{weeks} weeks'
ORDER BY completed_at
""", task_type)
10. Visualization Recommendations
Grid Layout:
Top: KPI cards (overall health, avg cycle time, throughput)
Middle: Comparative bar chart (workstreams)
Bottom: Trend line chart (90-day view)
Color Coding:
Green: Within SLA target
Yellow: 1-2x target
Red: >2x target
Gray: No data
Interactivity:
Filter by project/sprint/assignee
Zoomable time ranges
Click-through to underlying tasks
Export to CSV/PDF
This architecture provides:
Real-time monitoring with 15-min refresh
Workstream-specific metrics with appropriate thresholds
Actionable alerts when thresholds breached
Historical trending to track improvements
Scalable design handling 10k+ tasks per month
The system can be deployed on Kubernetes with:
PostgreSQL/TimescaleDB for storage
FastAPI for backend
React + Recharts/Chart.js for frontend
Celery for scheduled pipeline
Prometheus + Grafana for infrastructure monitoring
Which projects or labels to include/exclude.
Thresholds for alerts.
How often to fetch data.
SELECT
date_trunc('week', metric_date) as week,
task_type,
avg(avg_cycle_time) as week_avg_cycle_time, [but note: we have daily averages, so we need to weight by task_count?]
...
But note: the daily_metrics table already has the average for that day. If we want the average cycle time for the week, we need to compute the weighted average (by task_count) of the daily averages? Actually, we should compute from the raw tasks to get the true average for the week.
Alternatively, we can store the raw tasks and then compute the weekly average from the raw tasks? That would be more accurate.
But then we are back to querying the task_cycle_times table for the weekly aggregation.
Since we are storing the raw tasks, we can compute any aggregation from them.
So maybe we don't need the daily_metrics table? We can compute on the fly from task_cycle_times.
However, if we have a lot of tasks, computing medians and percentiles on the fly for a large date range might be slow.
Let's reconsider:
We have two use cases:
1. Dashboard that shows the latest metrics (last 7 days) and a trend (last 90 days) by week.
2. Control chart for a selected date range (maybe up to 90 days) and type.
For the trend, we want by week. We can compute from raw tasks:
For each week and type, we take all tasks completed in that week and compute the average, median, etc.
For the control chart, we want the individual tasks and the overall average and std dev for the selected period.
So we can do:
For the trend endpoint:
SELECT
date_trunc('week', completed_date) as week,
task_type,
avg(cycle_time_days) as avg_cycle_time,
median(cycle_time_days) as median_cycle_time,
percentile_cont(0.85) within group (order by cycle_time_days) as p85,
percentile_cont(0.95) within group (order by cycle_time_days) as p95,
count(*) as task_count
FROM task_cycle_times
WHERE completed_date between :start_date and :end_date
GROUP BY week, task_type
ORDER BY week, task_type;
For the control chart:
SELECT cycle_time_days, completed_date
FROM task_cycle_times
WHERE task_type = :type and completed_date between :start_date and :end_date
ORDER BY completed_date;
Then compute the average and std dev in the application (or in the query) for the entire set.
But note: the control chart might have a lot of points (if 90 days and many tasks). We might want to limit the number of tasks? Or we can paginate? But for control chart, we usually show all points.
Alternatively, we can pre-compute the weekly aggregates and store them in a table `weekly_metrics` to speed up the trend chart? But then we have to update the weekly metrics when new tasks are added.
Since we are already storing the raw tasks, and if the number of tasks is not huge (say, less than 100k), we can compute on the fly.
Let's assume we have up to 1000 tasks per week? Then 90 days is about 13 weeks, so 13,000 tasks. Computing percentiles on 13,000 rows is acceptable in PostgreSQL.
So we can skip the daily_metrics table and compute from raw tasks.
Then the fetcher only needs to store the raw tasks.
But then the dashboard for the latest metrics (last 7 days) would have to query the last 7 days of tasks and compute the metrics for each type? That might be acceptable.
However, if we want to show the latest metrics (for example, the average cycle time for the last 7 days for each type) we can compute:
SELECT
task_type,
avg(cycle_time_days) as avg_cycle_time,
median(cycle_time_days) as median_cycle_time,
...
FROM task_cycle_times
WHERE completed_date >= current_date - interval '7 days'
GROUP BY task_type;
This is a small query (only 7 days of tasks) so it's fast.
So we can avoid the daily_metrics table and compute on the fly.
But then we lose the ability to quickly get a time series of daily averages (if we want to show a daily trend for the last 90 days, we would compute 90 rows, which is also fast).
So let's simplify:
Only one table: task_cycle_times.
The fetcher:
- Fetches tasks (completed in the last day or since last run) from the issue tracker.
- For each task, compute cycle_time_days and insert (or update) into task_cycle_times.
The API:
GET /api/metrics/summary?days=7
Returns the average, median, etc. for the last N days (default 7) per task type.
GET /api/metrics/trend?start_date=...&end_date=...&group_by=day|week|month
Returns the metrics (avg, median, etc.) for each period (day, week, month) and task type.
GET /api/control-chart?task_type=...&start_date=...&end_date=...
Returns the individual tasks (cycle_time, completed_date) and the overall average and std dev for the period.
Then the frontend can:
- Show a table with the latest metrics (from /api/metrics/summary?days=7).
- Show a line chart for the trend (from /api/metrics/trend?group_by=week&start_date=...).
- Show a control chart for a selected type and date range (from /api/control-chart).
We can also have an endpoint to get the list of task types? Or we can hardcode UI, backend, ML.
It will:
- Connect to the issue tracker (using API token).
- Query for tasks that were completed in the last day (or since last run). How to get the last run? We can store the last fetched timestamp in a file or database? Or we can use the issue tracker's updated date and fetch tasks that were updated in the last day? But we only want completed tasks.
Let's assume the issue tracker has a field for completion date and we can query by that.
For Jira: we can use JQL: "status changed to Done after -1d"
For GitHub: we can query issues with "state=closed" and "closed_at after ..."
We also need to get the start date. In Jira, we might have a custom field for when it was moved to "In Progress". In GitHub, we might not have that. So we need to adapt to the issue tracker.
This is a challenge: different trackers have different ways to track start date.
Let's assume we have a way to get the start date (maybe the first time it was moved to an "In Progress" status, or the creation date if we don't have an "In Progress" status).
We'll abstract the issue tracker by having a base class and then implementations for Jira, GitHub, etc.
For simplicity, let's assume we are using Jira and we have a custom field "Start date" or we use the first time the issue was moved to "In Progress".
Steps for Jira:
JQL: "status changed to Done after -1d"
For each issue, get:
- key (task_id)
- status change history to find when it was moved to "In Progress" (or "Start date" field if available)
- resolution date (completed_date)
Then compute cycle_time_days = (resolution_date - start_date) in days (as a float, so we can have fractions).
Then insert into the database.
We must handle duplicates: if the same task was already fetched (same task_id and completed_date) then update the record? But if the start date changed? We can update if the fetched_at is newer? But note: the completed_date might be the same, but the start_date might have been corrected. So we can update the cycle_time_days if the new record has a different start_date? But then we are changing the cycle time for that task, which might affect the historical metrics.
Alternatively, we can store every fetch and then when we compute aggregates, we take the latest fetch? But then we have multiple records for the same task and same completed_date? That's why we have the unique constraint on (task_id, completed_date). So we can do an upsert: if the task_id and completed_date already exists, then update the cycle_time_days and fetched_at? But then we lose the previous value? But if the start_date changed, we want to update the cycle time? Yes.
So:
INSERT INTO task_cycle_times (task_id, task_type, cycle_time_days, completed_date, fetched_at)
VALUES (...)
ON CONFLICT (task_id, completed_date)
DO UPDATE SET
cycle_time_days = EXCLUDED.cycle_time_days,
fetched_at = EXCLUDED.fetched_at;
Then, after we have inserted/updated the tasks for a given set of completed_dates, we need to update the aggregates? But we are not storing aggregates in a separate table. So we don't need to update anything else.
Then the API will compute from the raw data, and it will use the latest cycle_time_days for each task (because we updated the record). But note: if we updated the cycle_time_days for a task, then the aggregates for that completed_date will change.
So the API queries will use the latest cycle_time_days for each task (because we updated the record). But note: we are storing the completed_date and task_id as unique, so we have only one record per task per completion. And we update that record if we fetch again and the start_date changed.
This should be acceptable.