ADR: What Azure charges
- Status
- accepted
- Date
- 2026-09-30
- Shipped as
- 1.0.3.55
Steve asked for the portal's subscription overview on the Admin tab, in public, since the bill is nothing to hide. A reader who sees how fast the site answers should see what it costs to run in the same place.
In plain words
This page puts the site's real Azure bill on the Admin tab for anyone to see: spending over time with Azure's forecast, and the cost broken down by resource and by type. The site's own identity asks the billing service (Azure Cost Management) once an hour and holds no key.
What that is worth: a developer sees what each part of the site costs beside how fast it answers, and the organization can show its running cost in public without exposing its subscription id.
Context
The Azure portal opens a subscription on four cards: the spending rate with a forecast, the cost by resource, the top resource types, and Defender coverage. The Admin tab already showed the milliseconds (the traffic, timing and machines cards) and the request units the document store charged, and the dollar figure lived only in the portal and on the Performance page, where it was typed from a price list on 20 September.
Read live on 30 September, with the subscription just renamed Stout-PayAsYouGo and its reactivation finished at about 15:30 CDT:
The month to date is more than the $22.38 list price on the Performance page because the two container groups the plan replaced ran until 20 September, and September's bill carries them.
Decision
The first three portal cards, on one workbench card called What Azure charges, under "Is it costing anything?": the spend over the window as a running total with Azure's forecast dashed to the month's end, the cost by resource as a donut that names the top four and folds the rest into Others, and the resources by type as bars. Public, like the rest of the tab, with no operator key. Defender coverage is left out, because it describes the subscription's security and this card is about its bill.
- Who asks. The site's own identity,
id-theyard-ss, the one that already reads Application Insights (ADR-024) and its own resource. It asks for a management token the same way, from whichever door the host has, and holds no key (ADR-072). It needed one role, Cost Management Reader on the subscription, which is free and adds nothing to the bill; Steve assigned it on 30 September and the probe read it back at 16:09.
- When it asks. Once an hour per site, from a background recorder, never on a request. Cost Management is rate limited and reports a day eight to twenty four hours late, so asking on every open of the card would spend the allowance on the same answer. The first read is half a minute after the site starts, so a roll costs one read and nothing else.
- What it asks. Two calls. The actual cost, daily, grouped by resource, for the last thirty-five days: one call answers the line and the donut, and thirty-five days is the month window and five more, because Azure revises a day after it ends. And the forecast for the month, which answers with the days Azure counts as billed and the days it forecasts; added up they are the month's forecast, the portal's own figure, and the days to come after the newest reported day are the dashed line. The resource types are read off the resource paths in the first answer, so the bars need no second role and no third call.
- What leaves the process. A resource's name and type, a day and a cost. The resource path carries the subscription's id, so it is cut down in the one method that reads the answer and never reaches the wire. A refusal is named for what it means (no role yet, slow down, the billing account is still being set up) and never quotes the service's own error, which names the scope it refused.
- Where the read is held. In memory, the last read only. The handoff for this change proposed a Cosmos DB container. Azure Cost Management is already the record of the bill and keeps it for the life of the subscription, so a copy here would be a second truth that could only drift from the first; the repository's first rule is to derive rather than store. What a roll loses is an hour's read, taken again thirty seconds later. The port the recorder writes through is the same shape a store would take, so a kept history is one adapter away if a year of bills is ever wanted on the card.
- The window. The same buttons as every other chart on the tab (ADR: The Admin tab, as a product). Azure bills by the day, so the day is the smallest grain: the last day is two days (yesterday whole, today as far as Azure has reported it), a week is seven and a month thirty, and the hour the other charts offer is shown as the last day, with a sentence that says so. The forecast is drawn on the month window, where its end is inside the chart.
- The newest day. Marked as still being added to while it is today or yesterday, on the line and in a sentence, because a total that is still moving should look like one.
- An absent reading. A sentence, never $0.00: off Azure ("a local run reads nothing"), before the first read, and without the role. A card that drew a zero for "no role yet" would be a false statement about the bill.
Money on this card is dollars and cents as a double, rounded to the cent. The repository's rule that money is whole dollars as int is about the auction, whose dataset prices are whole dollars and whose rules add whole-dollar increments. A bill is counted in cents.
What holds it
CostTests: a fixed Cost Management answer, with its columns out of the order the code asks for, becomes the expected days with no subscription path left in them; a nested type reads whole (a database is microsoft.sql/servers/databases); the forecast answer keeps each day marked billed or forecast by Azure's own status column; the donut folds past four; the newest day is flagged, a quiet day before it is a zero and a day after it is not drawn; each absent state is a sentence with nothing drawn; a refusal never quotes the scope; the held read is replaced whole; the reader's minute of cache holds; off Azure the recorder asks nobody; and the endpoint answers every window, and a window it does not know as the month.
PageStatusTests: the page sweep reads /api/admin/costs?window=30d at every roll, because a card that throws is a page that is down (ADR: Every page, checked at every roll).
spend.test.ts: the hour shown as the day, money as the bill writes it, the headline sentences, the axis's round top, the line turning to dashes where the reported days end, the donut's shares and the bars' lengths.
admin.spec.ts: with an answer in hand, the card draws the line, the donut with its legend, and the bars.
The shaping, the one method a subscription path passes through:
public static IReadOnlyList<CostDay> DaysFrom(JsonElement properties)
{
var columns = ColumnsOf(properties);
int cost = Find(columns, "Cost", "PreTaxCost", "CostUSD");
int date = Find(columns, "UsageDate");
int resource = Find(columns, "ResourceId");
int currency = Find(columns, "Currency", "BillingCurrency");
if (cost < 0 || date < 0)
{
return [];
}
var days = new List<CostDay>();
foreach (var row in RowsOf(properties))
{
string? day = DayOf(row[date]);
if (day is null)
{
continue;
}
var (name, type) = ResourceOf(resource < 0 ? null : row[resource].GetString());
days.Add(new CostDay(day, name, type, Number(row[cost]), currency < 0 ? "USD" : row[currency].GetString() ?? "USD"));
}
return days
.GroupBy(day => (day.Day, day.Resource, day.Type, day.Currency))
.Select(group => new CostDay(group.Key.Day, group.Key.Resource, group.Key.Type, PrintedNumber.Round(group.Sum(day => day.Cost), 4), group.Key.Currency))
.OrderBy(day => day.Day, StringComparer.Ordinal)
.ThenBy(day => day.Resource, StringComparer.Ordinal)
.ToList();
}
public static IReadOnlyList<CostForecastDay> ForecastFrom(JsonElement properties)
{
var columns = ColumnsOf(properties);
int cost = Find(columns, "Cost", "PreTaxCost", "CostUSD");
int date = Find(columns, "UsageDate");
int status = Find(columns, "CostStatus");
int currency = Find(columns, "Currency", "BillingCurrency");
if (cost < 0 || date < 0)
{
return [];
}
return RowsOf(properties)
.Select(row => (
Day: DayOf(row[date]),
Cost: Number(row[cost]),
Currency: currency < 0 ? "USD" : row[currency].GetString() ?? "USD",
Billed: status >= 0 && string.Equals(row[status].GetString(), "Actual", StringComparison.OrdinalIgnoreCase)))
.Where(row => row.Day is not null)
.GroupBy(row => (row.Day!, row.Currency, row.Billed))
.Select(group => new CostForecastDay(group.Key.Item1, PrintedNumber.Round(group.Sum(row => row.Cost), 4), group.Key.Currency, group.Key.Billed))
.OrderBy(day => day.Day, StringComparer.Ordinal)
.ToList();
}
public static (string Name, string Type) ResourceOf(string? resourceId)
{
if (string.IsNullOrWhiteSpace(resourceId))
{
return ("not tied to a resource", "other");
}
string path = resourceId.Trim().ToLowerInvariant();
int provider = path.LastIndexOf("/providers/", StringComparison.Ordinal);
if (provider < 0)
{
return (path.TrimEnd('/').Split('/')[^1], "other");
}
string[] parts = path[(provider + "/providers/".Length)..].Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3)
{
return (parts.Length == 0 ? "not tied to a resource" : parts[^1], "other");
}
var types = new List<string> { parts[0] };
for (int i = 1; i < parts.Length; i += 2)
{
types.Add(parts[i]);
}
return (parts[^1], string.Join('/', types));
}
private static Dictionary<string, int> ColumnsOf(JsonElement properties) =>
properties.TryGetProperty("columns", out var columns)
? columns.EnumerateArray()
.Select((column, index) => (Name: column.GetProperty("name").GetString() ?? "", Index: index))
.GroupBy(column => column.Name, StringComparer.OrdinalIgnoreCase)
.ToDictionary(group => group.Key, group => group.First().Index, StringComparer.OrdinalIgnoreCase)
: new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
private static IEnumerable<JsonElement> RowsOf(JsonElement properties) =>
properties.TryGetProperty("rows", out var rows) && rows.ValueKind == JsonValueKind.Array
? rows.EnumerateArray()
: [];
private static int Find(Dictionary<string, int> columns, params string[] names)
{
foreach (string name in names)
{
if (columns.TryGetValue(name, out int index))
{
return index;
}
}
return -1;
}
private static double Number(JsonElement value) => value.ValueKind switch
{
JsonValueKind.Number => value.GetDouble(),
JsonValueKind.String when double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out double parsed) => parsed,
_ => 0,
};
private static string? DayOf(JsonElement value)
{
string text = value.ValueKind == JsonValueKind.Number ? value.GetInt64().ToString(CultureInfo.InvariantCulture) : value.GetString() ?? "";
if (text.Length == 8 && DateOnly.TryParseExact(text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var compact))
{
return compact.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
return text.Length >= 10 && DateOnly.TryParseExact(text[..10], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dashed)
? dashed.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
: null;
}
Live from api/TheYard.Api/Shared/CostReadings/Costs.cs, region cost-shape, read from this build at 99df7a8.
The recorder, which is the only caller of Azure:
public sealed class CostRecorder(CostKeeping keeping, TimeSpan firstReadAfter, AlertRules? rules = null, TimeProvider? clock = null) : BackgroundService
{
public static readonly TimeSpan Every = TimeSpan.FromHours(1);
public static readonly TimeSpan Retry = TimeSpan.FromMinutes(5);
public static readonly TimeSpan ShortestSlowDown = TimeSpan.FromMinutes(1);
public static TimeSpan WaitAfter(CostOutcome outcome, TimeSpan? retryAfter = null) => outcome switch
{
CostOutcome.Failed => Retry,
CostOutcome.Refused when retryAfter is { } named =>
TimeSpan.FromTicks(Math.Clamp((named + TimeSpan.FromSeconds(30)).Ticks, ShortestSlowDown.Ticks, Every.Ticks)),
_ => Every,
};
public static TimeSpan FirstReadAfter(string? defaultStore) =>
string.Equals(defaultStore, StoreKeys.Document, StringComparison.OrdinalIgnoreCase)
? TimeSpan.FromSeconds(90)
: TimeSpan.FromSeconds(30);
public Task<CostOutcome> RecordOnceAsync(CancellationToken cancellation) => keeping.RecordOnceAsync(cancellation);
protected override async Task ExecuteAsync(CancellationToken stopping)
{
await Task.Delay(firstReadAfter, stopping).ContinueWith(_ => { }, TaskScheduler.Default);
while (!stopping.IsCancellationRequested)
{
CostOutcome outcome;
try
{
outcome = await keeping.TryRecordAsync(stopping);
if (!keeping.Configured)
{
return;
}
}
catch (OperationCanceledException) when (stopping.IsCancellationRequested)
{
return;
}
await RefreshRulesAsync(stopping);
await Task.Delay(keeping.KeptFor ?? WaitAfter(outcome, keeping.RetryAfter), stopping).ContinueWith(_ => { }, TaskScheduler.Default);
}
}
public async Task RefreshRulesAsync(CancellationToken stopping)
{
if (rules is null)
{
return;
}
try
{
await rules.RefreshAsync((clock ?? TimeProvider.System).GetUtcNow(), stopping);
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or System.Text.Json.JsonException && !stopping.IsCancellationRequested)
{
}
}
}
Live from api/TheYard.Api/Shared/CostReadings/CostRecorder.cs, region cost-recorder, read from this build at 99df7a8.
The view the cards are drawn from, and the cache in front of it:
public static class CostView
{
public const int Named = 4;
public static CostReport Build(string? window, CostKept kept, DateTimeOffset now, CostHistoryAvailability availability, (DateTimeOffset? At, bool Read, string? Note) last)
{
var (name, length) = CostWindows.Parse(window);
string today = now.UtcDay;
string first = now.AddDays(-(length - 1)).UtcDay;
string month = CostWindows.MonthOf(today);
string currency = kept.Days.FirstOrDefault()?.Currency ?? kept.Forecast.FirstOrDefault()?.Currency ?? "USD";
long? readAt = (kept.Days.Count > 0 ? kept.ReadAt ?? last.At : last.At)?.ToUnixTimeMilliseconds();
if (!availability.Available || kept.Days.Count == 0)
{
string note = !availability.Available
? availability.Reason
: last.Note ?? (last.At is null ? "the first hour's read has not landed yet; the recorder reads Azure half a minute after the site starts" : "Azure reported no charges for this subscription yet");
return CostReport.Absent(name, note, currency, readAt);
}
string newest = kept.Days.Max(day => day.Day)!;
bool partial = string.CompareOrdinal(newest, now.AddDays(-1).UtcDay) >= 0;
var inWindow = kept.Days.Where(day => string.CompareOrdinal(day.Day, first) >= 0 && string.CompareOrdinal(day.Day, today) <= 0).ToList();
var byDay = inWindow.GroupBy(day => day.Day).ToDictionary(group => group.Key, group => group.Sum(day => day.Cost), StringComparer.Ordinal);
var points = new List<CostPoint>();
double running = 0;
for (var day = DateOnly.ParseExact(first, "yyyy-MM-dd", CultureInfo.InvariantCulture); ; day = day.AddDays(1))
{
string key = day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
if (string.CompareOrdinal(key, newest) > 0 || string.CompareOrdinal(key, today) > 0)
{
break;
}
double cost = byDay.GetValueOrDefault(key);
running += cost;
points.Add(new CostPoint(key, Money(cost), Money(running), partial && key == newest));
}
var monthDays = kept.Days.Where(day => CostWindows.MonthOf(day.Day) == month).ToList();
double monthToDate = monthDays.Sum(day => day.Cost);
var answer = kept.Forecast.Where(day => CostWindows.MonthOf(day.Day) == month).ToList();
var ahead = answer
.Where(day => !day.Billed && string.CompareOrdinal(day.Day, newest) > 0)
.OrderBy(day => day.Day, StringComparer.Ordinal)
.ToList();
var forecast = new List<CostPoint>();
double projected = running;
foreach (var day in ahead)
{
projected += day.Cost;
forecast.Add(new CostPoint(day.Day, Money(day.Cost), Money(projected), false));
}
double? forecastMonth = answer.Count > 0 ? Money(monthToDate + ahead.Sum(day => day.Cost)) : null;
double? azureForecastMonth = answer.Count > 0 ? Money(answer.Sum(day => day.Cost)) : null;
var yesterday = YesterdayRate.For(kept.Days, newest, partial, month, monthToDate);
var rate = MonthRate.For(points, today);
return new CostReport(
name,
CostWindows.Names,
true,
last.Read ? null : last.Note,
currency,
readAt,
newest,
partial,
month,
Money(monthToDate),
forecastMonth,
Money(inWindow.Sum(day => day.Cost)),
rate.BilledDays,
rate.MonthDays,
points,
forecast,
Slices(inWindow, rate),
Kinds(inWindow, rate),
azureForecastMonth,
yesterday?.Month,
yesterday?.Day,
yesterday?.Cost)
{ SpikeDays = DaySpike.For(kept.Days, newest, partial) };
}
public static IReadOnlyList<CostSlice> Slices(IReadOnlyList<CostDay> days, MonthRate rate)
{
double total = days.Sum(day => day.Cost);
var ranked = days
.GroupBy(day => (day.Resource, day.Type))
.Select(group => (group.Key.Resource, group.Key.Type, Cost: group.Sum(day => day.Cost), Monthly: rate.Of(group)))
.Where(entry => entry.Cost > 0)
.OrderByDescending(entry => entry.Cost)
.ThenBy(entry => entry.Resource, StringComparer.Ordinal)
.ToList();
var slices = ranked.Take(Named)
.Select(entry => new CostSlice(entry.Resource, entry.Type, Money(entry.Cost), Money(entry.Monthly), Share(entry.Cost, total), 1))
.ToList();
var rest = ranked.Skip(Named).ToList();
if (rest.Count > 0)
{
double others = rest.Sum(entry => entry.Cost);
double othersMonthly = rest.Sum(entry => entry.Monthly);
slices.Add(new CostSlice("Others", "others", Money(others), Money(othersMonthly), Share(others, total), rest.Count));
}
return slices;
}
public static IReadOnlyList<CostKind> Kinds(IReadOnlyList<CostDay> days, MonthRate rate) =>
days
.GroupBy(day => day.Type)
.Select(group => new CostKind(
group.Key,
LabelOf(group.Key),
group.Select(day => day.Resource).Distinct(StringComparer.Ordinal).Count(),
Money(group.Sum(day => day.Cost)),
Money(rate.Of(group))))
.OrderByDescending(kind => kind.Cost)
.ThenByDescending(kind => kind.Resources)
.ThenBy(kind => kind.Label, StringComparer.Ordinal)
.ToList();
public static string LabelOf(string type) => type switch
{
"microsoft.web/sites" => "App Service apps",
"microsoft.web/serverfarms" => "App Service plans",
"microsoft.containerinstance/containergroups" => "Container instances",
"microsoft.containerregistry/registries" => "Container registries",
"microsoft.sql/servers/databases" => "SQL databases",
"microsoft.sql/servers" => "SQL servers",
"microsoft.documentdb/databaseaccounts" => "Azure Cosmos DB accounts",
"microsoft.insights/components" => "Application Insights",
"microsoft.operationalinsights/workspaces" => "Log Analytics workspaces",
"microsoft.communication/communicationservices" => "Communication Services",
"microsoft.communication/emailservices" => "Email Communication Services",
"microsoft.storage/storageaccounts" => "Storage accounts",
"microsoft.managedidentity/userassignedidentities" => "Managed identities",
"other" => "Not tied to a resource",
_ => type,
};
public static double Money(double value) => PrintedNumber.Round(value, 2, MidpointRounding.AwayFromZero);
private static double Share(double part, double total) => total <= 0 ? 0 : Math.Round(part / total * 100, 1);
}
public sealed class CostHistoryReader(ICostHistory history, CostReader reader, CostStatus status, TimeProvider clock, AlertRules? rules = null)
{
private readonly object _gate = new();
private readonly Dictionary<string, (DateTimeOffset At, CostReport View)> _cached = new(StringComparer.Ordinal);
public async Task<CostReport> ReadAsync(string? window, CancellationToken cancellation)
{
var now = clock.GetUtcNow();
string name = CostWindows.Parse(window).Name;
lock (_gate)
{
if (_cached.TryGetValue(name, out var hit) && now - hit.At < TimeSpan.FromMinutes(1))
{
return hit.View;
}
}
CostReport view;
if (!reader.Configured)
{
view = CostReport.Absent(name, CostReader.NotConfigured, "USD", null);
}
else
{
var availability = await history.AvailabilityAsync(cancellation);
var kept = availability.Available
? await history.ReadAsync(now.AddDays(-(CostWindows.ReadDays - 1)).UtcDay, cancellation)
: CostKept.Empty;
view = CostView.Build(name, kept, now, availability, status.Snapshot());
}
view = view with { Meters = MeterRows.From(rules?.Latest), BudgetDollars = MeterRows.Budget(rules?.Latest) };
lock (_gate)
{
_cached[name] = (now, view);
}
return view;
}
}
Live from api/TheYard.Api/Shared/CostReadings/CostReport.cs, region cost-view, read from this build at 99df7a8.
The tests that hold the view:
[Fact]
public void The_donut_names_four_resources_and_folds_the_rest_into_Others()
{
var days = new[] { 9.0, 5.0, 4.0, 3.0, 2.0, 1.0 }
.Select((cost, i) => new CostDay("2026-09-29", $"r{i}", "microsoft.web/sites", cost, "USD"))
.ToList();
var slices = CostView.Slices(days, new MonthRate(null, 1, 30));
Assert.Equal(new[] { "r0", "r1", "r2", "r3", "Others" }, slices.Select(slice => slice.Name));
Assert.Equal(3.0, slices[^1].Cost);
Assert.Equal(2, slices[^1].Count);
Assert.Equal(100.0, Math.Round(slices.Sum(slice => slice.Share), 0));
}
[Fact]
public void The_newest_day_is_flagged_partial_and_a_quiet_day_before_it_is_a_zero_not_a_gap()
{
var now = new DateTimeOffset(2026, 9, 30, 15, 0, 0, TimeSpan.Zero);
var kept = new CostKept(
[
new CostDay("2026-09-27", "aci-theyard-ss", "microsoft.containerinstance/containergroups", 1.0, "USD"),
new CostDay("2026-09-29", "aci-theyard-ss", "microsoft.containerinstance/containergroups", 0.5, "USD"),
],
[new CostForecastDay("2026-09-27", 1.0, "USD", Billed: true), new CostForecastDay("2026-09-29", 0.5, "USD", Billed: true), new CostForecastDay("2026-09-30", 0.25, "USD")]);
var report = CostView.Build("7d", kept, now, new CostHistoryAvailability(true, "kept"), (now, true, null));
Assert.True(report.Available);
Assert.Equal("2026-09-29", report.NewestDay);
Assert.True(report.NewestPartial);
Assert.Equal(new[] { "2026-09-24", "2026-09-25", "2026-09-26", "2026-09-27", "2026-09-28", "2026-09-29" }, report.Days.Select(day => day.Day));
Assert.Equal(0, report.Days.Single(day => day.Day == "2026-09-28").Cost);
Assert.True(report.Days[^1].Partial);
Assert.False(report.Days[^2].Partial);
Assert.Equal(1.5, report.Days[^1].Total);
Assert.Equal(1.5, report.MonthToDate);
Assert.Equal(1.75, report.ForecastMonth);
Assert.Equal(new[] { "2026-09-30" }, report.Forecast.Select(day => day.Day));
Assert.Equal(1.75, report.Forecast[0].Total);
Assert.Equal("Container instances", Assert.Single(report.Types).Label);
}
[Fact]
public void The_month_forecast_is_the_month_to_date_plus_the_days_ahead_never_Azures_lagging_sum()
{
var now = new DateTimeOffset(2026, 10, 24, 12, 0, 0, TimeSpan.Zero);
var kept = new CostKept(
[new CostDay("2026-10-01", "stjobhuntss", "microsoft.storage/storageaccounts", 45.21, "USD"), new CostDay("2026-10-23", "stjobhuntss", "microsoft.storage/storageaccounts", 24.99, "USD")],
[new CostForecastDay("2026-10-01", 45.84, "USD", Billed: true), new CostForecastDay("2026-10-25", 7.00, "USD"), new CostForecastDay("2026-10-26", 7.74, "USD")]);
var report = CostView.Build("30d", kept, now, new CostHistoryAvailability(true, "kept"), (now, true, null));
Assert.Equal(70.20, report.MonthToDate);
Assert.Equal(60.58, report.AzureForecastMonth);
Assert.Equal(84.94, report.ForecastMonth);
Assert.True(report.ForecastMonth >= report.MonthToDate);
}
[Fact]
public void With_no_days_ahead_the_month_forecast_is_the_month_to_date()
{
var now = new DateTimeOffset(2026, 10, 31, 20, 0, 0, TimeSpan.Zero);
var kept = new CostKept(
[new CostDay("2026-10-30", "plan-theyard-ss", "microsoft.web/serverfarms", 3.10, "USD")],
[new CostForecastDay("2026-10-30", 2.00, "USD", Billed: true)]);
var report = CostView.Build("7d", kept, now, new CostHistoryAvailability(true, "kept"), (now, true, null));
Assert.Equal(3.10, report.MonthToDate);
Assert.Equal(3.10, report.ForecastMonth);
Assert.Equal(2.00, report.AzureForecastMonth);
Assert.Empty(report.Forecast);
}
[Fact]
public void The_month_at_yesterdays_rate_is_the_finished_days_plus_yesterday_for_every_day_left()
{
var days = new[]
{
new CostDay("2026-10-22", "stjobhuntss", "microsoft.storage/storageaccounts", 13.41, "USD"),
new CostDay("2026-10-23", "stjobhuntss", "microsoft.storage/storageaccounts", 24.99, "USD"),
new CostDay("2026-10-24", "stjobhuntss", "microsoft.storage/storageaccounts", 0.28, "USD"),
};
var at = YesterdayRate.For(days, "2026-10-24", partial: true, "2026-10", monthToDate: 38.68);
Assert.NotNull(at);
Assert.Equal("2026-10-23", at.Value.Day);
Assert.Equal(24.99, at.Value.Cost);
Assert.Equal(238.32, at.Value.Month);
}
[Fact]
public void The_bars_put_the_costliest_type_first_and_a_type_billed_through_another_last()
{
var days = new[]
{
new CostDay("2026-09-30", "app-theyard-ss", "microsoft.web/sites", 0, "USD"),
new CostDay("2026-09-30", "app-theyard-cosmos-ss", "microsoft.web/sites", 0, "USD"),
new CostDay("2026-09-30", "app-theshed-ss", "microsoft.web/sites", 0, "USD"),
new CostDay("2026-09-30", "plan-theyard-ss", "microsoft.web/serverfarms", 0.26, "USD"),
new CostDay("2026-09-30", "sqldb-theyard-ss-basic", "microsoft.sql/servers/databases", 0.10, "USD"),
};
var kinds = CostView.Kinds(days, new MonthRate(null, 1, 30));
Assert.Equal(new[] { "App Service plans", "SQL databases", "App Service apps" }, kinds.Select(kind => kind.Label));
Assert.Equal(3, kinds[^1].Resources);
}
[Fact]
public void A_window_is_shown_as_a_month_at_the_rate_of_its_finished_days()
{
var now = new DateTimeOffset(2026, 10, 2, 13, 0, 0, TimeSpan.Zero);
var kept = new CostKept(
[
new CostDay("2026-10-01", "plan-theyard-ss", "microsoft.web/serverfarms", 0.43, "USD"),
new CostDay("2026-10-01", "sqldb-theyard-ss-basic", "microsoft.sql/servers/databases", 0.16, "USD"),
new CostDay("2026-10-01", "crtheyardss", "microsoft.containerregistry/registries", 0.15, "USD"),
new CostDay("2026-10-02", "plan-theyard-ss", "microsoft.web/serverfarms", 0.08, "USD"),
new CostDay("2026-10-02", "app-theyard-ss", "microsoft.web/sites", 0, "USD"),
],
[]);
var report = CostView.Build("24h", kept, now, new CostHistoryAvailability(true, "kept"), (now, true, null));
Assert.Equal(1, report.RateDays);
Assert.Equal(31, report.MonthDays);
var plan = report.Resources.Single(slice => slice.Name == "plan-theyard-ss");
Assert.Equal(0.51, plan.Cost);
Assert.Equal(13.33, plan.Monthly);
Assert.Equal(new[] { 13.33, 4.96, 4.65, 0 }, report.Types.Select(kind => kind.Monthly));
Assert.Equal(22.94, Math.Round(report.Types.Sum(kind => kind.Monthly), 2));
}
[Fact]
public void A_window_with_no_finished_day_is_scaled_from_the_days_it_has()
{
var points = new[] { new CostPoint("2026-10-02", 0.2, 0.2, true) };
var rate = MonthRate.For(points, "2026-10-02");
Assert.Null(rate.PartialDay);
Assert.Equal(1, rate.BilledDays);
Assert.Equal(6.2, CostView.Money(rate.Of([new CostDay("2026-10-02", "r", "t", 0.2, "USD")])));
}
[Fact]
public void An_absent_reading_says_why_in_a_sentence_and_draws_nothing()
{
var now = new DateTimeOffset(2026, 9, 30, 15, 0, 0, TimeSpan.Zero);
var noStore = CostView.Build("30d", CostKept.Empty, now, new CostHistoryAvailability(false, "no document store"), (null, false, null));
var noRole = CostView.Build("30d", CostKept.Empty, now, new CostHistoryAvailability(true, "kept"), (now, false, CostReader.NoRoleNote));
var notYet = CostView.Build("24h", CostKept.Empty, now, new CostHistoryAvailability(true, "kept"), (null, false, null));
Assert.Equal("no document store", noStore.Note);
Assert.Equal(CostReader.NoRoleNote, noRole.Note);
Assert.StartsWith("the first hour's read has not landed yet", notYet.Note);
foreach (var report in new[] { noStore, noRole, notYet })
{
Assert.False(report.Available);
Assert.Empty(report.Days);
Assert.Empty(report.Resources);
Assert.Null(report.ForecastMonth);
}
}
Live from api/TheYard.Tests/CostTests.cs, region cost-view-tests, read from this build at 99df7a8.
Addendum, 2026-09-30: the first read on the Cosmos DB site
Read live at 17:00 CDT, a minute after 1.0.3.55 rolled, uncached on both domains: the SQL site's card drew September at $47.24 with $49.03 forecast (aci-theyard-ss $21.97, aci-theyard-cosmos-ss $13.11, the registry $4.97, the same figures as the portal), and no answer carried the subscription's id. The Cosmos DB site's card said "the last read did not finish (TaskCanceledException); the next is in an hour": its first read, thirty seconds after the start, ran past the twenty seconds the reader allowed while the plan was still loading that site's catalogue, and the recorder then waited the full hour.
So from 1.0.3.56 the reader allows a minute, and a read that did not finish is tried again in five minutes. A read that went through, or one Azure refused, still waits the hour: a missing role does not appear in five minutes, and a request to slow down is a request to slow down.
public static TimeSpan WaitAfter(CostOutcome outcome, TimeSpan? retryAfter = null) => outcome switch
{
CostOutcome.Failed => Retry,
CostOutcome.Refused when retryAfter is { } named =>
TimeSpan.FromTicks(Math.Clamp((named + TimeSpan.FromSeconds(30)).Ticks, ShortestSlowDown.Ticks, Every.Ticks)),
_ => Every,
};
Live from api/TheYard.Api/Shared/CostReadings/CostRecorder.cs, region cost-retry, read from this build at 99df7a8.
Addendum, 2026-09-30: the bars measure dollars
At 19:28 CDT, on his phone, Steve reported that the bar chart on the Cosmos DB site's card was off. The bars measured how many resources of a type were on the bill and were ordered by that count, while each row printed the type's cost on its right. So the longest bar, at the top, was three App Service apps at $0.00, whose bill the plan carries, and a reader saw the biggest bar beside the smallest figure: two measures on one row, and the bar drew the one a bill is not read for.
From 1.0.3.57 a bar is a type's cost, a share of the costliest, ordered by cost; the count is in words beside the name. The apps still show, as an empty bar at $0.00 with "3 resources", which is the true picture: they are on the bill and the plan pays for them. The portal's own card counts resources; this one shows the money and keeps the count, because a reader of this tab came for what it costs.
Reading the card on the last day window, Steve pointed out that the total bill is about $48 a month, and asked for the conversion to happen in the C# code. The resource and type figures were what the window cost, so on the last day window the App Service plan read $0.48, one day of a plan that comes to about $14 a month, on a tab where the bill is read in months.
From 1.0.3.61 the server works out the month and the card only shows it. Each resource and each type carries monthly: what the window's finished days cost, divided by how many there are, times the days in the month. The newest day is left out while Azure is still adding to it, because part of a day counted as a whole one would pull the month down; a window with no finished day uses the days it has. The answer carries rate_days and month_days, and the card says in one sentence what rate its figures come from. The window total and the spend line stay in the window, because the line is a running total of real days.
Measured on 2 October: the one finished day in the last day window, 1 October, cost $0.74, which comes to $22.94 over October's 31 days. The last 30 days cost $45.74, and $32.82 of that was the two container instances, which the bill has not carried since 20 September.
public sealed record MonthRate(string? PartialDay, int BilledDays, int MonthDays)
{
public static MonthRate For(IReadOnlyList<CostPoint> points, string today)
{
var day = DateOnly.ParseExact(today, "yyyy-MM-dd", CultureInfo.InvariantCulture);
int monthDays = DateTime.DaysInMonth(day.Year, day.Month);
int finished = points.Count(point => !point.Partial);
string? partial = points.FirstOrDefault(point => point.Partial)?.Day;
return finished > 0
? new MonthRate(partial, finished, monthDays)
: new MonthRate(null, points.Count, monthDays);
}
public double Of(IEnumerable<CostDay> days) =>
BilledDays == 0 ? 0 : days.Where(day => day.Day != PartialDay).Sum(day => day.Cost) / BilledDays * MonthDays;
}
Live from api/TheYard.Api/Shared/CostReadings/CostReport.cs, region cost-rate, read from this build at 99df7a8.
Where it sits
The bill card spans three rings: CostHistory.cs in Application holds the ICostHistory port and, for now, its only implementation, CostsInMemory; the host holds the reader, the recorder and the shaping that strips the subscription id; src/lib/spend.ts lays out the card. Because CostRecorder writes through the port, a kept history would be one adapter and one line in Composition/CostRegistration.cs. It cost a Cost Management Reader role and up to an hour of staleness by design. A year of bills on the card would justify that adapter.
Addendum, 2026-10-17: the bill on the first screen
What Azure charges is on the landing page now, as the band's middle instrument: the month to date as a figure, a bar of it against the month's forecast, and the forecast printed after the fill. It is the same hourly read this record describes, handed out through /api/pulse rather than read again (ADR: One reading for the first screen), so the cost reader's rate to Azure is unchanged.
The honest-failure state travels with it. On a container with no identity to ask Azure with, the figure is the word unread and the track is empty, never a zero: a zero in that place claims the site is free.
Addendum, 2026-10-18: a slow-down waits as long as Azure says
Until this addendum, every refusal to read was waited for an hour. That held for a missing role, and it was wrong for a request to slow down. Both sites were rolled several times on 18 October, each roll started both first reads within the same second, and Cost Management answered 429 to both. The bill is held in memory, so the first screen's cost tile read unread on both sites until the next hourly read.
From 1.0.3.166 a 429 is waited exactly as long as Cost Management names in its headers, the standard Retry-After or the three x-ms-ratelimit-microsoft.costmanagement-*-retry-after it adds, taking the longest, plus half a minute, never under a minute and never over the hour. A refusal that names no wait is still an hour. The card's sentence says the wait it will actually take. And the site whose default store is the document store makes its first read a minute after the other site's, at 90 seconds rather than 30, so a roll of both no longer spends both first reads at once.
public static TimeSpan WaitAfter(CostOutcome outcome, TimeSpan? retryAfter = null) => outcome switch
{
CostOutcome.Failed => Retry,
CostOutcome.Refused when retryAfter is { } named =>
TimeSpan.FromTicks(Math.Clamp((named + TimeSpan.FromSeconds(30)).Ticks, ShortestSlowDown.Ticks, Every.Ticks)),
_ => Every,
};
Live from api/TheYard.Api/Shared/CostReadings/CostRecorder.cs, region cost-retry, read from this build at 99df7a8.
Addendum, 2026-10-24: the forecast is never below the spend
On 23 October the first screen read "forecast $61" under $70.20 already billed. The month's forecast was Azure's forecast answer added up, billed rows and days to come, which is the portal's own figure; but the answer's billed rows lag the actuals by a day or more, so on a bill that rose from $3.07 on 20 October to $24.99 on the 23rd the billed part summed to less than the month to date, and the forecast came out $9.62 below what was spent.
From 1.0.4.49 the month's forecast is the month to date plus Azure's forecast for each day after the newest day the bill has reported: $70.20 and $14.74 ahead, $84.94, never below the month to date, and the month to date itself when no day is ahead. Azure's own sum stays in the answer as azure_forecast_month, named for what it is, and the cost card says it beside the forecast only when it differs ("Azure's own sum reads $60.58: its billed days lag the bill, so it is below what is already spent"). The band's under-line reads "forecast $85", or "at least $70.20" if a forecast ever reads below the spend.
The card adds one more line, the month at yesterday's rate: the finished days plus the last finished day's cost for every day left (on the 24th, $38.40 and eight days at $24.99, $238.32). A spike shows as a projection the day it starts, where the 30-day average takes a week to move. The resource and type figures say which window their month is scaled from ("a month at the last 7 days' rate"), and the day window is never scaled to a month: it reads what yesterday and today have cost so far.
Addendum, 2026-11-07: graded on what is being spent, a spike guard, and the meters watched
Until this addendum the cost row was graded on Azure's forecast: red over $50, amber from $40, or when the forecast ran ahead of the month's own pace. On 4 November that read "$5.06 needs attention" because Azure's forecast replayed the October incident (the share's transactions, $3.07 to $24.99 a day from 20 to 23 October) into four days of November that had not happened. Steve's words that day: "can you check our billing, I thought we fixed this or is this just a spike from today", then "adjust it up 10$ then as we've added more resources" and "I'm just worried about extra large spikes".
From 1.0.4.155:
- The grade is what is being spent. The tone is the budget's lines over the larger of the month so far and the month at yesterday's rate; Azure's forecast is printed beside it as "Azure's forecast $X" and decides nothing. The budget is $60, amber at $50 ($10 under it, the line he named, not a share of it).
src/lib/ranges.ts holds both and the rule; the template infra/jobhunt-budget.bicep says 60.
- A spike is a day rule. A day is red when it costs more than three times the median of the finished week before it, and never under $5, so a $1.45 week does not flag a $4.40 day while 21 October's $7.82 would have tripped it. The spike rule is applied to the newest two days (the last finished day and the one Azure is still adding to) before the month's lines, so a spike reads red the day it starts. The server ships the facts (
DaySpike.cs: each day, its median and how many days that median is over, the multiple, and the resource with the biggest line), as spike_days; the line and the tone live once, in ranges.ts.
- Every meter that can run away has a rule that emails within the hour, because Cost Management reports a day late: blob transactions and egress on the job-hunt account, Log Analytics ingestion against the workspace's 0.1 GB daily cap, email sends, Function executions and the web plan's bytes out, in
infra/jobhunt-meters.bicep beside the share's existing rule; Cost Management's own anomaly alert in infra/jobhunt-anomaly.bicep. Each line is about four times the busiest quiet hour of the week before it was set. Priced from Azure's retail price list on 7 November: a metric rule $0.10 a month, a log rule checked hourly $0.50, so the six new rules add about $1.00 a month, inside the $2 a month approved for alerts on 18 October.
- The card says which rules exist.
AlertRules.cs reads the metric and log rules in both resource groups, the budgets and the anomaly alerts with the site's own identity, an hour apart beside the bill; MeterRows.cs joins each named meter to its rule by name, as meters on the wire. A rule that exists and is on reads fine; one that waits for its deploy reads unjudged, never red, because a missing alert needs nobody at three in the morning.
The budget keeps its three notices at the new amount, the forecast one included; Azure's forecast may still replay October this month, so that notice can email while the card reads green.
export const MONTHLY_BUDGET_DOLLARS = 70;
export const BUDGET_AMBER_DOLLARS = MONTHLY_BUDGET_DOLLARS - 10;
export const SPIKE_MULTIPLE = 3;
export const SPIKE_FLOOR_DOLLARS = 5;
export const RANGES = {
memory: {
name: 'Memory of its limit',
unit: '%',
amber: 0.8,
red: 0.95,
source: 'the container is restarted by the platform at its limit; 80% leaves room for a burst',
},
p95: {
name: 'Ninety-fifth answer time',
unit: 'ms',
amber: 1_000,
red: 3_000,
source: 'ADR-080: a second is slow to a visitor, three seconds is broken',
},
coldStart: {
name: 'Cold start, ready',
unit: 'ms',
amber: 30_000,
red: 60_000,
source:
'measured at 26,677 ms on the live site; past a minute the platform warm-up probe gives up',
},
ruMinute: {
name: 'Busiest minute of the free request units',
unit: '%',
amber: 0.5,
red: 0.9,
source: 'the free tier carries 1,000 RU a second; past 90% a burst is billed or throttled',
},
sqlDtu: {
name: 'Azure SQL busiest share',
unit: '%',
amber: 0.6,
red: 0.9,
source: 'the serverless tier scales at its ceiling; 60% is the early look',
},
keptWarm: {
name: 'Slowest kept-warm read',
unit: 'ms',
amber: 1_000,
red: 3_000,
source: 'the same lines as an answer a visitor waits for',
},
cost: {
name: "The month, at yesterday's rate",
unit: '$',
amber: BUDGET_AMBER_DOLLARS,
red: MONTHLY_BUDGET_DOLLARS,
source:
"Steve's budget: $60 on 11/4 (\"adjust it up 10$ then as we've added more resources\"), $70 on 11/11, read from Azure's budget when the cost read carries it; red at the budget, amber $10 under it, graded on what is being spent, never on Azure's forecast",
},
clientErrorsHour: {
name: 'Turned away (4xx) in the hour',
unit: '',
amber: 50,
red: 200,
source:
'a quiet hour turns away a handful of scanners; 50 is a crawl, 200 is an attack or a broken link',
},
gateSeconds: {
name: 'The gate, start to verdict',
unit: 's',
amber: 300,
red: 600,
source: 'ADR-068: every check in under five minutes',
},
liveSeconds: {
name: 'Push to live',
unit: 's',
amber: 900,
red: 1800,
source:
'GATEFLOW1117: push to live read 929 s at 1.0.5.75, and R1 aims at a version every 16 to 20 minutes, so a quarter of an hour is the target and half an hour the red line',
},
certificateDays: {
name: 'Days left on the certificate',
unit: 'days',
amber: 30,
red: 7,
lowIsBad: true,
source: 'the platform renews at 30 days; under a week a renewal has failed',
},
sqlStorage: {
name: 'Azure SQL storage of its tier',
unit: '%',
amber: 0.8,
red: 0.95,
source: 'the tier holds 2 GB and refuses writes when full',
},
} satisfies Record<string, Range>;
Live from src/lib/ranges.ts, region ranges, read from this build at 99df7a8.
Addendum, 2026-11-09 (1.0.4.165): a long type name stays inside the card
On the live bill the cost card ran 3 to 6 px past its edge at a phone and at a desk, and no local run saw it, because a local run reads no bill. The cause was the bill itself. Two of its types have no label in the cost reader, so the card hands their Azure type to the bar's name: "microsoft.insights/scheduledqueryrules" is one word with nowhere to break, and the bar's head would not shrink it.
From this version a bar's name breaks a long token at its own dots and slashes, the cut the log card already makes for an address (tableFit's addressParts), and never inside a word. The bar's ceiling, "4 resources", keeps its width beside it. admin.spec feeds the card the live bill's two unlabelled types and its longest meter rule at 390 and 1,280 px, and holds every element of the card inside its edge and the page from scrolling sideways; without the change a span ran 22.8 px past the card at 390. The card's own scroll width is not read, because it rounds a fraction of a pixel up on every bill, long names or not.
Addendum, 2026-11-10 (1.0.5.12): the last read is kept across rolls
What stopped being true: "Where the read is held. In memory, the last read only ... What a roll loses is an hour's read, taken again thirty seconds later." On 10 November, after twelve versions that day (1.0.4.176 to 1.0.5.8), each a roll of the one web app that serves both names, the first screen's "Azure this month" read "unread" on 1.0.5.8 and the cost route said "Cost Management asked this site to slow down; the next read is in an hour". Every roll started a process with nothing held, its first read came thirty seconds in, Cost Management answered 429 to the many reads the rolls added up to, the recorder waited the hour a 429 with no Retry-After costs, and the card had no days to show for that hour.
The last read is kept in the relational store. One table, CostReads, one row: when the read was answered, its days and its forecast as the cost port's own records in JSON, the same thing the in-memory copy holds and replaced whole the same way. KeptCosts holds the read in this process and keeps it in the row (EfCostStore); it answers from its own copy while that copy is under an hour old, and past that, or with nothing held, from the row, so a process that has just rolled starts with the last bill. Azure Cost Management is still the record of the bill; the row is the site's last reading of it, as the memory always was, and it lasts as long as the database does instead of as long as the process.
A roll spends nothing. Before a read the keeping asks for the kept one: under an hour old, it is this hour's read, the recorder waits out the rest of the hour, and Cost Management is not asked. One read an hour is taken, however many times the site rolls in that hour, while the row is kept: where the store is not attached or a save fails, the read is held in memory only, as before, and a roll inside the hour reads again.
A refused read shows the kept bill. When a read is refused or fails and a bill is kept, the card shows that bill, with the time it was read and the reason the newer read did not come; "unread" is left for when nothing has ever been kept.
The table on Azure SQL. Published with sqlpackage on 10 November at 21:12 CST, by this version's lane, after a deploy report showed the one change, [dbo].[CostReads], and nothing else; the report after the publish showed no difference. The live database is sqldb-theyard-ss-basic (the examples in ADR-040 and ADR-041 name an earlier sqldb-theyard-ss, which is empty). The site's user holds db_datareader and db_datawriter, which reach the new table. On SQLite the migration CostReads makes it. Where the store is not attached, or the table is not published, the history says so on the card's reason line and holds the read in memory as before.
Corrected in 1.0.5.14: this addendum first said each roll was a blue-green roll of two slots and that the slot that did not read answered from the one that did. One web app serves both names and a roll swaps it with no second copy (ADR: Blue-green on a $13 plan, measured and held, the addendum of 1.0.4.24), so there is one reader an hour, not two; the kept row is what carries the bill across the swap.
KeptCostsTests builds the history the way the site does, over a real SQLite store, and holds the three cases: a roll with a read kept twenty minutes ago shows the bill and does not read again; a 429 with a bill kept two hours ago shows that bill as of its read, with the slow-down note; a 429 with nothing kept is unread and says why. With the history wired back to the in-memory one the first two are red.
Addendum, 2026-11-17 (1.0.5.76): the card's line is the budget Azure holds
What stopped being true: that the cost row's red line is a number typed into the page. Steve raised the budget to $70 on 11 November and Azure's budget-subscription-monthly now holds $70 (set 16 November), while the Overview still graded the month against $60. The row now grades against the amount Azure's budget holds whenever the cost read carries it (budget_dollars, read with the alert rules), amber $10 under it as before, and against $70 only when that field is missing or null; its range line names whichever budget it used. The Spend and forecast card says why Azure's dashed forecast can sit above the month's own pace: the forecast weighs earlier months, spikes and all (it read $70.75 on 16 November against about $58 a month at that week's rate). The grade still never reads the forecast.
Addendum, 2026-11-17 (1.0.5.79): what Cosmos DB's charge is
In plain words: the document store is on the free tier, which covers its throughput and its first 25 GB, and it still costs about $10 a month. Read on the bill by meter, all of it is one thing: data the account sends out of its region. The account is in West US 2 and the site that reads it is in West US 3, so every read crosses between the two. The Cosmos DB card now says so, with both regions read live.
The read, Cost Management's query API by resource and meter for the 30 days to 15 November: cosmos-theyard-ss, "Inter Region Data Transfer Out", $5.45, and no other meter; over 9 to 15 November it was $0.349 a day, as much as the file share. The account's region is its own record's location; the site's is App Service's REGION_NAME, which the platform sets on every web app.
It is not waste to cut by turning something off: the site reads the store on every Cloud card's minute and every visitor's request. Two things shrink it. Fewer reads send fewer bytes, which the recorders' change in ADR-102's addendum of this day began. And the account could move to the site's region, which would end the meter, but moving a Cosmos DB account means adding a region and failing over, a change to the store everything rests on and Steve's to make; the card names the two regions so the choice is in front of him. CosmosBillTests holds the card's row.
Enforced by
2 rules in the rulebook cite this record, each held by a test on every release.