Skip to content

ADR: What Azure charges

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:

Reading Value Where it was read
Month to date $47.18, every cent of it in RG-THEYARD-SS Cost Management, grouped by resource group, 16:09 CDT
Forecast for September $49.03: $45.85 billed through 28 September and $3.18 forecast for the last two days Cost Management's forecast, 16:09 CDT, the same figure the portal showed at 15:36
Rows for 35 days by resource 198, one page, four columns: Cost, UsageDate, ResourceId, Currency Cost Management, 16:09 CDT
Newest day 30 September, $0.48 so far the same read

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:

/// <summary>
/// A page of actual cost, as the days the store keeps. Cost Management
/// answers with columns and rows, and the columns are read by name, never
/// by position, because the order is the service's to change. The resource
/// path is cut to its name and type here, so the subscription's id never
/// leaves this method, let alone reaches the wire.
/// </summary>
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"));
    }

    // Two rows for one resource on one day are one charge: a grouped query
    // should not return them, and the cards count each pair once.
    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();
}

/// <summary>A page of forecast: every day the answer carries, each marked billed or forecast by the service's own status column.</summary>
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();
}

/// <summary>
/// A resource path as a name and a type. The type is every type segment
/// after the last provider, so a database is microsoft.sql/servers/databases
/// and not a server; the name is the last segment. A charge with no
/// resource (a tax line, a marketplace line) is kept under a name that says
/// so rather than dropped, because it is still on the bill.
/// </summary>
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");
    }

    // namespace, then type and name in pairs: the types are the odd places.
    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));
}

/// <summary>
/// Each column's place in a row, by the column's name in any case, so a row is read by name and
/// not by position.
/// </summary>
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);

/// <summary>The rows of an answer, or none when the answer carries no row array.</summary>
private static IEnumerable<JsonElement> RowsOf(JsonElement properties) =>
    properties.TryGetProperty("rows", out var rows) && rows.ValueKind == JsonValueKind.Array
        ? rows.EnumerateArray()
        : [];

/// <summary>
/// The place of the first of <paramref name="names"/> the answer has, or -1 when it has none of
/// them.
/// </summary>
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;
}

/// <summary>
/// A cost cell as a number; the service sends a number or a numeric string, and anything else
/// counts as zero.
/// </summary>
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,
};

/// <summary>The service writes a day as the number 20260930 in one answer and a date string in another; both are read.</summary>
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:

/// <summary>
/// Reads Cost Management once an hour and holds the answer (ADR: What Azure
/// charges). Never on a request: the service is rate limited, lags the day by
/// eight to twenty four hours, and a card that asked it on every open would
/// spend the allowance on the same answer.
///
/// <para>This type is the schedule and nothing else: the wait after start, the wait after each
/// answer, and the loop between them. The read itself and everything it leaves behind are
/// <see cref="CostKeeping"/>, which is why this is handed four things rather than six: the keeping, the wait, and the
/// rules on the meters with the clock their read is stamped with.</para>
/// </summary>
/// <param name="keeping">One read of the bill, kept, with its failures already written down.</param>
/// <param name="firstReadAfter">How long after the start the first read waits (see <see cref="FirstReadAfter"/>).</param>
/// <param name="rules">The rules on the meters, read beside the bill; null where nothing reads them.</param>
/// <param name="clock">The clock a read of the rules is stamped with.</param>
public sealed class CostRecorder(CostKeeping keeping, TimeSpan firstReadAfter, AlertRules? rules = null, TimeProvider? clock = null) : BackgroundService
{
    /// <summary>How often the bill is read.</summary>
    public static readonly TimeSpan Every = TimeSpan.FromHours(1);

    /// <summary>How soon a read that did not finish is tried again.</summary>
    public static readonly TimeSpan Retry = TimeSpan.FromMinutes(5);

    /// <summary>The least a request to slow down is waited, whatever it named.</summary>
    public static readonly TimeSpan ShortestSlowDown = TimeSpan.FromMinutes(1);

    // #region cost-retry
    /// <summary>
    /// How long to wait after a read. An hour after one that went through,
    /// and after one Azure refused for want of a role, which does not appear
    /// in five minutes. Five minutes after one that did not finish, because a
    /// timeout says nothing about the next answer, and an hour of an empty card
    /// for one slow answer is the wrong trade. A request to slow down is
    /// waited exactly as long as Azure named, plus half a minute, between one
    /// minute and an hour; when it named nothing, an hour
    /// (ADR: What Azure charges, addenda).
    /// </summary>
    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,
    };
    // #endregion cost-retry

    /// <summary>
    /// How long after the start the first read waits. Where each site has a process of its own and
    /// both roll together, the one whose default store is the document store waits a minute longer,
    /// so the two first reads never reach Cost Management in the same second; the one web app that
    /// serves both sites sets no default store and waits the shorter time.
    /// </summary>
    /// <param name="defaultStore">The store this process serves by default, or null when it serves both.</param>
    public static TimeSpan FirstReadAfter(string? defaultStore) =>
        string.Equals(defaultStore, StoreKeys.Document, StringComparison.OrdinalIgnoreCase)
            ? TimeSpan.FromSeconds(90)
            : TimeSpan.FromSeconds(30);

    /// <summary>One read, public so the suite can run one without waiting an hour; says how it went.</summary>
    /// <param name="cancellation">The read's cancellation.</param>
    public Task<CostOutcome> RecordOnceAsync(CancellationToken cancellation) => keeping.RecordOnceAsync(cancellation);

    /// <summary>
    /// The loop: a short wait after start (see FirstReadAfter), then a read, then a wait set by how the read went.
    /// A run that is not on Azure stops after its first read, since there is nothing to ask with.
    /// </summary>
    /// <param name="stopping">The host's stopping token, which ends the loop.</param>
    protected override async Task ExecuteAsync(CancellationToken stopping)
    {
        // A short wait after the start, so the first read never competes with
        // the catalogue this process loads as it starts, and the two sites'
        // first reads land a minute apart.
        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);
        }
    }

    /// <summary>
    /// The rules on the meters, read beside the bill. A read that throws keeps the last good answer: the rules
    /// change seldom, and a card that blanked them for one slow answer would say less than it knows.
    /// </summary>
    /// <param name="stopping">The host's stopping token.</param>
    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)
        {
            // The rules stay as last read; the bill's own status line says how the bill went.
        }
    }
}

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:

/// <summary>
/// The last read, shaped for the three cost cards (ADR: What Azure charges):
/// the spend over the window with the forecast to the month's end, and what
/// each resource and each type of resource cost, in the window and as a month
/// at the window's rate. Pure, so a fixed set of days in gives a fixed answer
/// out and a test can hold it.
/// </summary>
public static class CostView
{
    /// <summary>How many resources the donut names before it folds the rest into Others.</summary>
    public const int Named = 4;

    /// <summary>
    /// The cards' answer for one window: the spend line with its forecast, the month so far,
    /// and the resources and types. With no days kept, or no store to keep them in, the answer
    /// says why in a sentence instead.
    /// </summary>
    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";
        // The time the shown bill was read: the kept read's, so a refused read beside a kept bill says how old the bill
        // is; the last try's when nothing is kept.
        long? readAt = (kept.Days.Count > 0 ? kept.ReadAt ?? last.At : last.At)?.ToUnixTimeMilliseconds();

        if (!availability.Available || kept.Days.Count == 0)
        {
            // Absent is said in a sentence, never drawn as a zero: a card that
            // showed $0.00 for "no role yet" would be a false statement about the bill.
            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)!;
        // Azure lags the day by eight to twenty four hours, so the newest day
        // it has reported is still being added to until it is two days old.
        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);

        // Every day from the window's first to the newest Azure has reported:
        // a day before the newest with no rows cost nothing, and a day after
        // it has not been reported, so it is left off rather than drawn as zero.
        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);
        // The dashed line is the days to come after the newest day the bill has reported, from Azure's
        // forecast answer. The month's forecast is the month to date plus those days (ADR: What Azure
        // charges): the answer's own sum is kept beside it as Azure's figure, because its billed rows lag
        // the actuals, so on a rising bill it reads below what is already spent.
        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) };
    }

    /// <summary>
    /// What each resource cost in the window and what that comes to in a month,
    /// largest first, the top four by name and the rest as Others.
    /// </summary>
    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;
    }

    /// <summary>
    /// What each type of resource cost in the window, what that comes to in a
    /// month, and how many of it are on the bill, the costliest first. A type the
    /// bill carries at $0.00, such as App Service apps whose plan pays for them,
    /// goes last, so the longest bar is where the money went.
    /// </summary>
    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();

    /// <summary>A resource type in the words the portal uses for it; a type this list does not know is shown as Azure names it.</summary>
    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,
    };

    /// <summary>Money to the cent, which is what the bill shows.</summary>
    public static double Money(double value) => PrintedNumber.Round(value, 2, MidpointRounding.AwayFromZero);

    /// <summary>A part's share of a total, in percent to one place; zero when the total is nothing.</summary>
    private static double Share(double part, double total) => total <= 0 ? 0 : Math.Round(part / total * 100, 1);
}

/// <summary>
/// The last read, served to the cards, each window cached for a minute: the
/// Admin tab is a page somebody leaves open, and the read under it changes
/// once an hour (ADR: What Azure charges).
/// </summary>
public sealed class CostHistoryReader(ICostHistory history, CostReader reader, CostStatus status, TimeProvider clock, AlertRules? rules = null)
{
    /// <summary>The lock around the cache.</summary>
    private readonly object _gate = new();

    /// <summary>The last answer per window and when it was built, keyed by the window's name.</summary>
    private readonly Dictionary<string, (DateTimeOffset At, CostReport View)> _cached = new(StringComparer.Ordinal);

    /// <summary>
    /// The answer for a window: from the cache when it is under a minute old, built fresh from the
    /// kept days otherwise.
    /// </summary>
    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"),
        ],
        // The forecast answer as Azure gives it: the billed days, then the days to come.
        [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);
    // The window's first day is 24 September and the newest reported is the 29th: six days, the 28th a zero.
    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()
{
    // 23 October as it read: $70.20 billed, Azure's answer adding up to $60.58 because its billed rows
    // lag the actuals, and $14.74 forecast for the days after the newest reported.
    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()
{
    // 24 October at noon: the 23rd finished at $24.99, the 24th has $0.28 so far.
    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);
    // 38.40 finished, then eight days (24th to 31st) at $24.99.
    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));

    // The apps cost nothing on their own: the plan carries their bill, so they go last.
    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()
{
    // The 24 hour window on 2 October: 1 October finished at $0.74, and 2 October still being added to.
    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));

    // One finished day, scaled to the 31 days of October; the partial day is left out of the rate.
    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.

/// <summary>
/// How long to wait after a read. An hour after one that went through,
/// and after one Azure refused for want of a role, which does not appear
/// in five minutes. Five minutes after one that did not finish, because a
/// timeout says nothing about the next answer, and an hour of an empty card
/// for one slow answer is the wrong trade. A request to slow down is
/// waited exactly as long as Azure named, plus half a minute, between one
/// minute and an hour; when it named nothing, an hour
/// (ADR: What Azure charges, addenda).
/// </summary>
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.

Addendum, 2026-10-02: every figure as a month

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.

/// <summary>
/// How a window's cost becomes a month's: what the 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 a 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, so the card still shows a figure rather than nothing.
/// </summary>
/// <param name="PartialDay">The day left out, as yyyy-MM-dd, or null when every day counts.</param>
/// <param name="BilledDays">How many days the month figure is scaled from.</param>
/// <param name="MonthDays">How many days the month has.</param>
public sealed record MonthRate(string? PartialDay, int BilledDays, int MonthDays)
{
    /// <summary>The rate for a window's days, in the month that holds today.</summary>
    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);
    }

    /// <summary>What these days come to in a month at this rate.</summary>
    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.

Files

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.

/// <summary>
/// How long to wait after a read. An hour after one that went through,
/// and after one Azure refused for want of a role, which does not appear
/// in five minutes. Five minutes after one that did not finish, because a
/// timeout says nothing about the next answer, and an hour of an empty card
/// for one slow answer is the wrong trade. A request to slow down is
/// waited exactly as long as Azure named, plus half a minute, between one
/// minute and an hour; when it named nothing, an hour
/// (ADR: What Azure charges, addenda).
/// </summary>
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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.

/**
 * The owner's monthly budget for the whole subscription: over it the cost reads red. The card grades against the
 * amount Azure's own budget holds when the cost read carries it, and against this number only when it does not.
 */
export const MONTHLY_BUDGET_DOLLARS = 70;

/** Ten dollars under the budget, the amber line the owner named, rather than a share of it. */
export const BUDGET_AMBER_DOLLARS = MONTHLY_BUDGET_DOLLARS - 10;

/** A day costs this many times the week's median before it reads as a spike. */
export const SPIKE_MULTIPLE = 3;

/** And never less than this, so a cheap week does not flag an ordinary day. */
export const SPIKE_FLOOR_DOLLARS = 5;

/** Every judged number, by key. A share is written from 0 to 1 and said as a percentage. */
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.

The rule What holds it In the last gate
The bill on the Admin tab is read from Azure once an hour and never on a request, a resource path is cut to its name and type before anything reaches the wire, the donut names four resources and folds the rest into Others, and a reading that is absent is a sentence and never a zero CostTests 64 of 64 passed
The cost is graded on the month at yesterday's rate against the budget Azure holds ($70 when the read carries none), a day over three times the median of the week before it (never under $5) is red first, and every meter that can run away is joined by name to the rule that emails for it, unjudged and never red while a rule waits CostSpikeTests, TemplateTests, spendSpike.test.ts, ranges.test.ts 14 of 14 passed
Store

The Yard, home

Steven StoutStaff .NET engineerRemote

Production .NET that stays up. Built with AI, measured on every version.

Steven Stout

Hi, I'm Steve. I build the systems that make delivery boring in the best way, then coach people inside them.

  • 200+

    production releases, none took the platform down

    Conway Investment Research, 2019 to 2024. Sole engineer for the first three years on a live financial advisory platform.

    See how
  • 50%

    shorter release cycle

    Storee Construction, 2024 to 2026. Four ASP.NET applications onto one .NET 10 platform on Azure, with a four-person team I hired and mentored.

    See how

01Verified

Steven Stout

A real person, and the work is mine.

  • Identity

    Checked by LinkedIn, not by me.

    LinkedIn verified my government ID.

  • Running system

    You are looking at it.

    Version 1.0.5.273 is live. Nothing ships unless it passes the automated gates first.

That's who I am. Here's how I work.

02Strengths

Ten strengths, each with the proof beside it. The numbers match my resume and LinkedIn, and the live ones are read from this site as you look.

  • 01

    Keeps production alive

    200+ releases on a live financial platform, and none took it down. Sole engineer for the first three years.

    See the Conway work

  • 02

    Simplifies messy systems

    Four ASP.NET applications onto one .NET 10 platform on Azure, and a release cycle 50% shorter.

    See the Storee work

  • 03

    Marries dev and infrastructure

    Blue-green releases at Storee that flipped in about 5 seconds with nobody signed out, and Azure Front Door at two employers.

    See this site's cloud

  • 04

    Designs data that holds up

    White-label clients on one shared database, the isolation built into the data, and no cross-client issues.

    See the Conway work

  • 05

    Keeps AI-written code honest

    15 quality numbers that may only improve: 273 releases in a row with none worse.

    See the quality numbers

  • 06

    Resourceful

    $30,000+ cut from Azure and vendor spend at Conway. This site's Azure bill is public, resource by resource.

    See the bill

  • 07

    Builds people up

    Hired and mentored a four-person team. 13 colleagues recommend me by name.

    Read the recommendations

  • 08

    Takes ideas to production

    This site: designed, built and run solo, with 352 versions measured through one gate.

    How it was built

  • 09

    Writes clearly

    Posts on real engineering problems, in plain words.

    Read the blog

  • 10

    Owns decisions

    153 decision records, each with its tradeoff and the call I made.

    See the decision records

Built with AI. Gated so quality never slides.

Steven Stout’s showcase: a used-vehicle auction on .NET and React, built and run by one engineer, live on Azure, with its decisions written down.

No quality number has gotten worse at any release since 1.0.5.1 on 10 November: 273 releases in a row.

One engineer, an AI agent and a gate that checks 15 quality numbers on every release. 352 versions measured, with every result public, the worst days included.

82 releases in the last 7 days, each through the same gate.

Async methods with no CancellationToken, may only fall

11091.0.3.1391.0.5.2731.0.4.115, the ratchet
Every number, on the Quality page

TheYard, right nowLive

Answering in

unread

02505007501,000

server time at p95, the usual five minutes of the last day.

Azure this month

unread

the bill, by resource, read from Azure. The Admin tab shows every line.

Since the last roll

unread

 

rolled in place by the pipeline, behind one gate.

People who have visited

unread

30 days agotoday

Scanners, my own tools' and my own reads left out.

03Start here

04Where teams are heading

How I see engineering with AI, and the setup on this site that backs it.

AI-augmented teams · Architecture and ownership

AI writes more of the code. Someone still has to own what ships.

Teams are going to be heavily AI-augmented. That moves the senior job toward architecture and technical ownership: deciding what to build in pieces small enough to verify, and owning what ships.

  • Task tracking will get automated too. Judgment stays human: seeing a design fail at scale before it does.
  • On this site the AI's first design held the whole catalogue in memory. I caught it when the App Service plan hit 82 per cent and moved the work to the store.

What the AI wrote, what I decided

07Tech stack

  •    
  •    
  •    

Read from the build, never typed by hand

What TheYard runs on

What we use, where it runs, its AWS twin, the version as built, and the file that proves it.

Cloud patterns, not one vendor: every Azure piece in this stack has a named AWS twin. Mapped, not yet run on AWS.

  • .NET 1114 projects
  • React 19.3TypeScript 7.0
  • Azure9 Bicep files
  • 11GitHub Actions workflows
The whole stack, with the file that proves each line

The last release the gate stopped was 1.0.5.258 on 2 December, at its browser 1 of 2 job.

08How it is built

09How it is run

10Who and why

Next step

11What has to work, where is it today, and what does success look like?

Book 20 minutes opens an email to me with those three questions in it, and I answer with a time.

Book 20 minutes

Your email app should have opened with this message. If it did not, copy it and send it from any mailbox.

Or message me on LinkedIn