SLA control with data: business hours, holidays, pauses, and breach risk in Python
SLA, SLO, SLI, and OLA without confusion, a priority matrix, business-hours math with Brazilian holidays and pauses, compliance by priority and team, breach prediction, a 75% warning, error budgets, and how to avoid watermelon metrics.
Data$ python -m unittest test_sla▍“We met 90% of the SLA” sounds like good news until someone asks: 90% of what? Counting weekends? And the November 20 holiday? And the tickets that sat for three days in “waiting on customer”? An SLA number is only as good as the math behind it. In this guide you’ll write and test that math in Python, compute compliance by priority and team, predict breaches on open tickets, and build a report that doesn’t hide problems.
The tickets come from the synthetic generator in incident analysis for DevOps and helpdesk; save that tickets.py in the same folder.
SLA, SLO, SLI, and OLA
Google’s SRE book defines the SLI as a carefully defined quantitative measure of some aspect of the level of service. The SLO is the target value for that SLI. The SLA is the agreement with consequences, such as penalties or credits, if the SLO is missed. Without an explicit consequence, what you have is an SLO. The OLA comes from ITIL: it’s the internal agreement between teams of the same provider that supports the SLA. The ITIL definitions below are paraphrased.
| Term | What it is | Who agrees on it | Example |
|---|---|---|---|
| SLI | The measurement | Engineering | % of P3 tickets resolved within 24 business hours |
| SLO | The target for the SLI | Engineering and product | 95% of P3 on time, per month |
| SLA | The contract with consequences | Provider and customer | 90% on time, or a credit on the invoice |
| OLA | The internal agreement behind the SLA | Teams of the same provider | DBA responds to the service desk within 2 business hours |
Keep the internal SLO tighter than the SLA: it warns you before the contract breaks.
Priority matrix and example policy
Priority usually comes from an impact × urgency matrix. Impact says how many users or how much of the business is affected; urgency says how fast the damage grows.
| Impact \ Urgency | High | Medium | Low |
|---|---|---|---|
| High (service down for many) | P1 | P2 | P3 |
| Medium (group or function degraded) | P2 | P3 | P4 |
| Low (one user, with a workaround) | P3 | P4 | P4 |
Each priority has two targets: response (first human acknowledgement) and resolution. This is an example policy, not a recommendation:
| Priority | Response | Resolution | Clock |
|---|---|---|---|
| P1 | 15 min | 4 h | 24×7 |
| P2 | 30 min | 8 h | 24×7 |
| P3 | 4 business h | 24 business h | Mon–Fri, 8 a.m.–6 p.m. |
| P4 | 8 business h | 40 business h | Mon–Fri, 8 a.m.–6 p.m. |
Business time with holidays and pauses
The business clock here is Monday to Friday, 8 a.m. to 6 p.m., in the America/Sao_Paulo time zone, minus the national holidays from the holidays package. In version 0.109, holidays.Brazil() and holidays.country_holidays("BR") include November 20 (National Day of Zumbi and Black Awareness). Carnival and Corpus Christi are in the optional category (categories=("public", "optional")). For state holidays, use subdiv: with subdiv="SP", July 9 is included. language="en_US" gives English holiday names.
The function walks day by day, intersects business hours with the interval, and adds them up. Pauses are subtracted with the same function, after merging overlapping ones:
from dataclasses import dataclass, field
from datetime import datetime, time, timedelta
from zoneinfo import ZoneInfo
import holidays
TZ = ZoneInfo("America/Sao_Paulo")
@dataclass(frozen=True)
class Calendar:
opens: int = 8 # opening hour
closes: int = 18 # closing hour
days: frozenset = frozenset(range(5)) # 0 = Monday ... 4 = Friday
holidays: object = field(default_factory=lambda: holidays.Brazil(language="en_US"))
tz: ZoneInfo = TZ
BUSINESS = Calendar()
H24 = Calendar(opens=0, closes=24, days=frozenset(range(7)), holidays={})
def business_seconds(start, end, calendar):
"""Business seconds between start and end according to the calendar."""
if start.tzinfo is None or end.tzinfo is None:
raise ValueError("use timezone-aware datetimes")
if end <= start:
return 0.0
start, end = start.astimezone(calendar.tz), end.astimezone(calendar.tz)
total, day = 0.0, start.date()
while day <= end.date():
if day.weekday() in calendar.days and day not in calendar.holidays:
midnight = datetime.combine(day, time(), calendar.tz)
open_at = midnight + timedelta(hours=calendar.opens)
close_at = midnight + timedelta(hours=calendar.closes)
a, b = max(open_at, start), min(close_at, end)
if b > a:
total += (b - a).total_seconds()
day += timedelta(days=1)
return total
def merge(intervals):
"""Merge overlapping pauses so the same time is not subtracted twice."""
merged = []
for a, b in sorted(intervals):
if merged and a <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], b))
else:
merged.append((a, b))
return merged
def sla_time(start, end, pauses, calendar):
"""Ticket business time minus pauses (e.g. waiting on customer)."""
gross = business_seconds(start, end, calendar)
paused = sum(business_seconds(max(a, start), min(b, end), calendar)
for a, b in merge(pauses))
return gross - paused
Three decisions are worth pointing out. The function rejects naive datetimes, because mixing UTC and local time is the most common SLA bug. The 24×7 calendar is just another Calendar, so P1 and P2 use the same code. And the pause is measured on the ticket’s own calendar: an overnight pause subtracts nothing from a P3.
Tests for the tricky cases
import unittest
from datetime import datetime
from sla import BUSINESS, H24, TZ, business_seconds, sla_time
H = 3600
def dt(text):
return datetime.fromisoformat(text).replace(tzinfo=TZ)
class TestBusinessSeconds(unittest.TestCase):
def test_same_day(self):
self.assertEqual(business_seconds(dt("2026-11-24 09:00"), dt("2026-11-24 11:30"), BUSINESS), 2.5 * H)
def test_overnight(self): # Mon 5pm -> Tue 9am: 1h + 1h
self.assertEqual(business_seconds(dt("2026-11-23 17:00"), dt("2026-11-24 09:00"), BUSINESS), 2 * H)
def test_weekend(self): # Fri 4pm -> Mon 10am: 2h + 2h
self.assertEqual(business_seconds(dt("2026-11-27 16:00"), dt("2026-11-30 10:00"), BUSINESS), 4 * H)
def test_holiday_november_20(self): # Thu 5pm -> Mon 9am, Friday 11/20 is a holiday
self.assertEqual(business_seconds(dt("2026-11-19 17:00"), dt("2026-11-23 09:00"), BUSINESS), 2 * H)
def test_holiday_november_15_on_a_weekday(self): # 11/15/2027 is a Monday
self.assertEqual(business_seconds(dt("2027-11-12 17:00"), dt("2027-11-16 09:00"), BUSINESS), 2 * H)
def test_outside_business_hours(self): # a whole Saturday does not count
self.assertEqual(business_seconds(dt("2026-11-28 09:00"), dt("2026-11-28 17:00"), BUSINESS), 0)
def test_24x7(self): # Fri 4pm -> Mon 10am, wall clock
self.assertEqual(business_seconds(dt("2026-11-27 16:00"), dt("2026-11-30 10:00"), H24), 66 * H)
def test_other_timezone(self): # 12:00 UTC = 9am in São Paulo
start = datetime.fromisoformat("2026-11-24 12:00+00:00")
self.assertEqual(business_seconds(start, dt("2026-11-24 10:00"), BUSINESS), 1 * H)
def test_naive_fails(self):
with self.assertRaises(ValueError):
business_seconds(datetime(2026, 11, 24, 9), datetime(2026, 11, 24, 10), BUSINESS)
def test_waiting_on_customer_pause(self): # 13 business hours - 6h of business-hour pause
pauses = [(dt("2026-11-24 14:00"), dt("2026-11-25 10:00"))]
self.assertEqual(sla_time(dt("2026-11-24 09:00"), dt("2026-11-25 12:00"), pauses, BUSINESS), 7 * H)
def test_overlapping_pauses(self): # 10-12 and 11-13 = 3h of pause, not 4h
pauses = [(dt("2026-11-24 10:00"), dt("2026-11-24 12:00")),
(dt("2026-11-24 11:00"), dt("2026-11-24 13:00"))]
self.assertEqual(sla_time(dt("2026-11-24 08:00"), dt("2026-11-24 18:00"), pauses, BUSINESS), 7 * H)
if __name__ == "__main__":
unittest.main()
...........
----------------------------------------------------------------------
Ran 11 tests in 0.000s
OK
In 2026, November 15 falls on a Sunday and doesn’t change the math; that’s why the test uses 2027, when it falls on a Monday. The same cases, in business and wall-clock hours:
from datetime import datetime
from sla import BUSINESS, H24, TZ, business_seconds, sla_time
def dt(text):
return datetime.fromisoformat(text).replace(tzinfo=TZ)
cases = [
("overnight", "2026-11-23 17:00", "2026-11-24 09:00", []),
("weekend", "2026-11-27 16:00", "2026-11-30 10:00", []),
("holiday 11/20 (Fri)", "2026-11-19 17:00", "2026-11-23 09:00", []),
("with pause", "2026-11-24 09:00", "2026-11-25 12:00",
[("2026-11-24 14:00", "2026-11-25 10:00")]),
]
for name, start, end, pauses in cases:
p = [(dt(a), dt(b)) for a, b in pauses]
business = sla_time(dt(start), dt(end), p, BUSINESS) / 3600
wall = business_seconds(dt(start), dt(end), H24) / 3600
print(f"{name:<22} business={business:>4.1f} h wall clock={wall:>4.1f} h")
print(BUSINESS.holidays.get("2026-11-20"))
overnight business= 2.0 h wall clock=16.0 h
weekend business= 4.0 h wall clock=66.0 h
holiday 11/20 (Fri) business= 2.0 h wall clock=88.0 h
with pause business= 7.0 h wall clock=27.0 h
National Day of Zumbi and Black Awareness
From Thursday 5 p.m. to Monday 9 a.m., 88 wall-clock hours go by, but only 2 business hours. A report that measures in wall-clock hours would show a P3 like that as breached.
Compliance by priority and team
The module below applies the policy to the tickets, generates synthetic “waiting on customer” pauses (on purpose, the network team pauses more), and computes, for each ticket, how much of the target has been consumed. Open tickets are measured up to “now”, November 25, 2026.
import numpy as np
import pandas as pd
from sla import BUSINESS, H24, TZ, business_seconds, sla_time
from tickets import NOW, generate_tickets
NOW_TZ = NOW.tz_localize(TZ)
# example policy: (response, resolution, calendar)
POLICY = {
"P1": (pd.Timedelta(minutes=15), pd.Timedelta(hours=4), H24),
"P2": (pd.Timedelta(minutes=30), pd.Timedelta(hours=8), H24),
"P3": (pd.Timedelta(hours=4), pd.Timedelta(hours=24), BUSINESS),
"P4": (pd.Timedelta(hours=8), pd.Timedelta(hours=40), BUSINESS),
}
def generate_pauses(df, seed=7):
"""Synthetic 'waiting on customer' pauses on P3/P4; the network team pauses more."""
rng = np.random.default_rng(seed)
pauses = {}
for t in df.itertuples():
end = t.resolved_at if pd.notna(t.resolved_at) else NOW_TZ
chance = 0.5 if t.team == "network" else 0.15
if t.priority in ("P3", "P4") and rng.random() < chance:
start = t.opened_at + (end - t.opened_at) * rng.uniform(0.1, 0.5)
pauses[t.id] = [(start, start + (end - start) * rng.uniform(0.2, 0.7))]
return pauses
def load():
df = generate_tickets()
for col in ["opened_at", "acknowledged_at", "resolved_at"]:
df[col] = df[col].dt.tz_localize(TZ)
pauses = generate_pauses(df)
rows = []
for t in df.itertuples():
resp_target, res_target, cal = POLICY[t.priority]
ack = t.acknowledged_at if pd.notna(t.acknowledged_at) else NOW_TZ
end = t.resolved_at if pd.notna(t.resolved_at) else NOW_TZ
p = pauses.get(t.id, [])
rows.append({
"response_h": business_seconds(t.opened_at, ack, cal) / 3600,
"resolution_h": sla_time(t.opened_at, end, p, cal) / 3600,
"pause_h": (business_seconds(t.opened_at, end, cal) / 3600
- sla_time(t.opened_at, end, p, cal) / 3600),
"response_target_h": resp_target / pd.Timedelta(hours=1),
"resolution_target_h": res_target / pd.Timedelta(hours=1),
})
df = pd.concat([df, pd.DataFrame(rows)], axis=1)
df["is_open"] = df["resolved_at"].isna()
df["consumed"] = df["resolution_h"] / df["resolution_target_h"] # 1.0 = 100% of target
df["resolution_breached"] = df["consumed"] > 1
df["response_breached"] = df["response_h"] > df["response_target_h"]
# counterfactual: what if pauses were not subtracted?
df["breached_without_pause"] = (df["resolution_h"] + df["pause_h"]) > df["resolution_target_h"]
return df
from sla_base import load
df = load()
print(f"Resolution SLA, overall: {1 - df['resolution_breached'].mean():.1%}\n")
by_prio = df.groupby("priority").agg(
tickets=("id", "size"),
response_ok=("response_breached", lambda s: 1 - s.mean()),
resolution_ok=("resolution_breached", lambda s: 1 - s.mean()),
near_miss=("consumed", lambda s: s.between(0.9, 1).sum()),
)
print(by_prio.round(3).to_string(), "\n")
by_team = df.groupby("team").agg(
resolution_ok=("resolution_breached", lambda s: 1 - s.mean()),
ok_without_pause_discount=("breached_without_pause", lambda s: 1 - s.mean()),
tickets_with_pause=("pause_h", lambda s: (s > 0).mean()),
)
print(by_team.sort_values("resolution_ok").round(3).to_string(), "\n")
breaches = df[df["resolution_breached"]].sort_values("consumed", ascending=False)
print(f"resolution breaches: {len(breaches)}, still open: {breaches['is_open'].sum()}")
print(breaches[["id", "priority", "team", "category", "resolution_h",
"resolution_target_h", "consumed"]].head(5).round(1).to_string(index=False))
Resolution SLA, overall: 89.6%
tickets response_ok resolution_ok near_miss
priority
P1 93 0.925 0.796 4
P2 323 0.833 0.697 8
P3 994 0.996 0.939 13
P4 724 1.000 0.938 14
resolution_ok ok_without_pause_discount tickets_with_pause
team
dba 0.763 0.741 0.089
platform 0.824 0.817 0.094
network 0.857 0.819 0.267
infra 0.919 0.909 0.071
service-desk 0.955 0.951 0.092
resolution breaches: 223, still open: 1
id priority team category resolution_h resolution_target_h consumed
INC-00928 P2 infra monitoring 99.9 8.0 12.5
INC-01504 P2 platform application 55.9 8.0 7.0
INC-00467 P2 network vpn 54.3 8.0 6.8
INC-00547 P2 platform deploy 47.3 8.0 5.9
INC-00950 P2 platform application 45.6 8.0 5.7
The overall number, 89.6%, looks acceptable. By priority, the story changes: P1 meets 79.6% and P2 only 69.7%. Those are exactly the tickets that hurt the most, and they vanish in the average because there are few of them. The near_miss column counts tickets closed between 90% and 100% of the target; a near miss is the warning that the margin is gone.
By team, network shows 85.7%, but pauses 26.7% of its tickets, versus about 9% for the others. Without subtracting pauses, it would drop to 81.9%. The pause may be legitimate, but it has to show up in the report. The breach list shows the worst cases by ID, so someone can open them and understand.
Breach risk on open tickets
Measuring after the deadline passed is an autopsy. For open tickets, the useful question is “will this one breach?”. A simple, explainable answer: take the closed tickets of the same priority that had already passed this one’s elapsed time. Look at the p90 of how much longer they took and what fraction of them breached. If the remaining p90 is greater than the time left, the ticket goes to “watch”; if 30% or more of the peers breached, it becomes “high risk”. At 75% of the target, the warning fires anyway.
import pandas as pd
from sla_base import load
df = load()
history = df[~df["is_open"]]
open_tickets = df[df["is_open"]].copy()
def risk(t):
"""Compare with closed tickets of the same priority that had already passed
this ticket's elapsed time: how much longer they took and how many breached."""
peers = history[(history["priority"] == t.priority)
& (history["resolution_h"] > t.resolution_h)]
if len(peers) < 20:
return float("nan"), float("nan") # small sample: do not invent a forecast
p90 = (peers["resolution_h"] - t.resolution_h).quantile(0.9)
return p90, (peers["resolution_h"] > t.resolution_target_h).mean()
open_tickets[["p90_remaining_h", "breach_prob"]] = [risk(t) for t in open_tickets.itertuples()]
open_tickets["remaining_h"] = open_tickets["resolution_target_h"] - open_tickets["resolution_h"]
def status(t):
if t.consumed > 1:
return "BREACHED"
if t.consumed >= 0.75:
return "WARNING 75%"
if t.breach_prob >= 0.3:
return "high risk"
if t.p90_remaining_h > t.remaining_h:
return "watch"
return "ok"
open_tickets["status"] = [status(t) for t in open_tickets.itertuples()]
print(open_tickets["status"].value_counts().to_string(), "\n")
columns = ["id", "priority", "team", "resolution_h", "remaining_h",
"p90_remaining_h", "breach_prob", "status"]
print(open_tickets.sort_values(["consumed"], ascending=False)[columns]
.head(6).round(2).to_string(index=False))
# warnings before the breach, without repeating the same warning every run
THRESHOLDS = [(1.0, "BREACHED"), (0.75, "WARNING 75%")]
def warnings(open_tickets, already_sent):
for t in open_tickets.itertuples():
crossed = [name for limit, name in THRESHOLDS if t.consumed >= limit]
if crossed and (t.id, crossed[0]) not in already_sent:
already_sent.update((t.id, name) for name in crossed) # highest covers the lower ones
deadline = (f"{t.remaining_h:.1f} h left" if t.remaining_h > 0
else f"breached {-t.remaining_h:.1f} h ago")
yield f"[{crossed[0]}] {t.id} {t.priority}/{t.team}: {t.consumed:.0%} of target, {deadline}"
already_sent = set() # in production, store this in a database or Redis
print()
for msg in warnings(open_tickets, already_sent):
print(msg)
print("second run:", list(warnings(open_tickets, already_sent)))
status
ok 21
watch 13
high risk 4
WARNING 75% 2
BREACHED 1
id priority team resolution_h remaining_h p90_remaining_h breach_prob status
INC-01959 P4 network 47.57 -7.57 49.11 1.00 BREACHED
INC-02035 P3 dba 20.00 4.00 21.77 0.76 WARNING 75%
INC-02063 P3 dba 20.00 4.00 21.77 0.76 WARNING 75%
INC-02131 P2 dba 5.90 2.10 22.79 0.76 high risk
INC-02073 P3 network 17.17 6.83 22.83 0.50 high risk
INC-02014 P4 service-desk 28.18 11.82 30.29 0.42 high risk
[BREACHED] INC-01959 P4/network: 119% of target, breached 7.6 h ago
[WARNING 75%] INC-02035 P3/dba: 83% of target, 4.0 h left
[WARNING 75%] INC-02063 P3/dba: 83% of target, 4.0 h left
second run: []
INC-02131 is a P2 with 74% of the target consumed: it hasn’t reached 75% yet, but 76% of its peers breached. That’s the kind of ticket a fixed-threshold warning doesn’t catch yet. Deduplication makes sure each warning goes out only once per level; on the second run the list is empty. A scikit-learn classifier could estimate the risk right at opening time, using priority, team, category, and time of day. It was left out to keep the rule auditable; the path is in machine learning with scikit-learn.
The SLO error budget
The error budget is 1 − SLO over the period. With an SLO of 95% of P3 tickets on time per month, every 100 P3 tickets allow 5 breaches. When the budget runs out, the team stops accepting risky changes and works on the cause. The culture behind this is in SLO and error budget culture, and choosing the target in SLOs that make business sense.
from sla_base import load
SLO = 0.95 # 95% of P3 tickets resolved within SLA, per month
df = load()
p3 = df[df["priority"] == "P3"].copy()
p3["month"] = p3["opened_at"].dt.strftime("%Y-%m")
monthly = p3.groupby("month").agg(tickets=("id", "size"), breaches=("resolution_breached", "sum"))
monthly["budget"] = (monthly["tickets"] * (1 - SLO)).round(1) # allowed breaches
monthly["consumed"] = (monthly["breaches"] / monthly["budget"]).map("{:.0%}".format)
print(monthly.to_string())
tickets breaches budget consumed
month
2026-08 49 1 2.5 40%
2026-09 320 22 16.0 138%
2026-10 373 24 18.7 128%
2026-11 252 14 12.6 111%
August has only five days of data. From September to November, the budget was blown every month: 138%, 128%, and 111% so far. P3 tickets meet 93.9%, close to the SLO, but consistently below it. That calls for reliability work, like the recurring VPN problem, not another push to close tickets.
Honest reporting: no watermelon metrics
A watermelon metric is green on the outside and red on the inside: the dashboard says everything is fine and the customer disagrees. To avoid it:
- Break it down by priority and team. The 89.6% total was hiding P2 at 69.7%.
- Count open tickets. An open ticket past its deadline is a breach today, not when it closes.
- Show pauses. Publish the share of paused tickets and the compliance without the pause discount.
- Publish near misses and the p90, not just the on-time percentage.
- Don’t change the priority to fit the target. Downgrading a P2 to P3 makes the report green and the customer angry.
- Measure in business hours only when the contract says so. And keep the calendar definition with the report.
If tickets carry names, emails, or phone numbers, treat them as personal data under privacy laws such as Brazil’s LGPD or the GDPR: the SLA math needs none of that, so export only IDs and timestamps.
Checklist
- I wrote down the SLI, SLO, SLA, and OLA for each service, with the internal SLO tighter than the SLA
- I have the impact × urgency matrix and separate response and resolution targets
- I measure business time with time zones,
holidaysholidays, and pauses, with tests for overnight, weekends, holidays, and pauses - I report compliance by priority and team, with near misses and open tickets already breached
- I publish the share of paused tickets and the compliance without the pause discount
- I warn at 75% of the target and use history (p90) to flag risk before the threshold
- I track the SLO error budget and change the team’s priorities when it runs out
A good SLA isn’t the one that’s always green: it’s the one that turns red in time for someone to act.