ADR: The App Service plan, read every minute
- Status
- accepted
- Date
- 2026-10-18
The Admin tab gains a Cloud infrastructure section, and its first card reads the App Service plan the web apps run on (two since 19 October: the one web app for every .NET process, and the rendering service): the plan's processor and memory as live dials, thirty days of both with every deploy and every Azure platform event drawn on the same line, the apps the plan carries, and the plan's own events. One document a minute is kept in Cosmos DB for thirty-one days and the card reads the kept copy; Azure Monitor is asked only when the newest kept minute is older than a minute.
In plain words
The portal shows what the machine is doing. The deploy pipeline shows what the code did. Neither page knows about the other, so when something goes wrong the first twenty minutes of any review go to lining up timestamps from two tools.
This card puts both on one line. Memory that steps up at a deploy marker changed because the code changed, which is a decision. Memory that climbs between markers is a leak. Memory that drops at a red line was Azure restarting the worker. One line, three readings, and nobody has to ask the other team.
What that is worth: the people who write the code and the people who run it look at the same screen and see the same information.
Context
Since 1.0.0.156 both sites run as web apps on one Linux App Service plan (ADR: One plan, two sites), and since the rendering service (ADR: A rendering service beside the API) a third app, the Node renderer, sits on the same plan. The plan moved from B1 to B2 on 8 October when its memory read 91 per cent at the median, so it is two virtual processors and 3.5 GB, and three apps share it. Two of them hold a 100,000-vehicle catalogue in memory each, so memory is the resource that runs out first, and the plan's dashboard in the portal is the only place that said so.
The site already keeps what its own machines are doing, one document a minute (ADR: What the machines are doing), and what Azure charges, one read an hour (ADR: What Azure charges). Both read Azure with the container's managed identity and keep the answer in Cosmos DB so the Admin tab never waits on Azure. The plan's metrics are the missing third source, and they follow the same shape.
Decision
One recorder, one document a minute, written by one site. PlanRecorder asks Azure Monitor once a minute for the plan's metrics at one-minute grain, and for each of the three apps' own metrics, and writes one document to the plan container partitioned on the UTC day. Only the site whose default store is the relational one records, the rule the machines recorder already follows, so two sites never write the same minute twice. The Activity Log and the three apps' state, always-on setting and last deploy are read once an hour, because they change at most that often.
public sealed class PlanRecorder(PlanReader reader, IPlanHistory history, BuildInfo build, TimeProvider clock, ILogger<PlanRecorder> logger) : BackgroundService
{
public static readonly TimeSpan Lookback = TimeSpan.FromMinutes(5);
public DateTimeOffset? Newest { get; private set; }
private readonly Dictionary<DateTimeOffset, string> _keptMinutes = [];
public int MinutesWritten { get; private set; }
private DateTimeOffset? _hourRead;
public async Task<int> RecordOnceAsync(CancellationToken cancellation)
{
if (!reader.Configured || !(await history.AvailabilityAsync(cancellation)).Available)
{
return 0;
}
var now = clock.GetUtcNow();
var minutes = await reader.ReadMinutesAsync(now - Lookback, now, build.Version, cancellation);
foreach (var minute in minutes)
{
string values = System.Text.Json.JsonSerializer.Serialize(minute);
if (_keptMinutes.TryGetValue(minute.At, out string? kept) && kept == values)
{
continue;
}
await history.AppendMinuteAsync(minute, cancellation);
_keptMinutes[minute.At] = values;
MinutesWritten++;
}
foreach (var old in _keptMinutes.Keys.Where(at => at < now - Lookback - TimeSpan.FromMinutes(5)).ToList())
{
_keptMinutes.Remove(old);
}
if (minutes.Count > 0)
{
Newest = minutes.Max(minute => minute.At);
}
var hour = MachineWindows.BucketOf(now, MachineGrain.Hour);
if (_hourRead != hour)
{
await history.AppendHourAsync(await reader.ReadHourAsync(hour, _hourRead ?? hour.AddHours(-1), cancellation), cancellation);
_hourRead = hour;
}
return minutes.Count;
}
protected override async Task ExecuteAsync(CancellationToken stopping)
{
while (!stopping.IsCancellationRequested)
{
try
{
if (!reader.Configured)
{
return;
}
await RecordOnceAsync(stopping);
var now = clock.GetUtcNow();
await Task.Delay(now.UtcMinute.AddMinutes(1).AddSeconds(10) - now, stopping);
}
catch (OperationCanceledException) when (stopping.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
logger.LogWarning("A minute of the plan could not be kept ({Exception} {Status})", ex.GetType().Name, (ex as HttpRequestException)?.StatusCode);
await Task.Delay(TimeSpan.FromMinutes(1), stopping).ContinueWith(_ => { }, TaskScheduler.Default);
}
}
}
}
Live from api/TheYard.Api/Shared/PlanReadings/PlanRecorder.cs, region plan-recorder, read from this build at 99df7a8.
Kept thirty-one days, served from the kept copy. The container's own time to live is thirty-one days, one more than the longest window the tab offers, so the container is its own retention policy. GET /api/admin/plan?window=24h|7d|30d answers from Cosmos DB alone. A live read happens only when the newest kept minute ended more than sixty seconds ago, which is the case for the first minute after a cold start and never otherwise. Azure Monitor metric reads are free; the writes are about 43,000 a month at roughly 1.3 request units each, inside the free tier the account already runs on.
{
"container": "plan",
"partitionKeyPath": "/day",
"defaultTtlSeconds": 2678400,
"why": "The App Service plan, kept: one document a minute with the plan's own readings from Azure Monitor and one per app on it, and one document an hour with the apps' states and the Activity Log, all partitioned on the UTC day and written by the SQL site alone so a minute is never written twice. The kind, the day, the minute, the three bucket keys and the figures the windows average are indexed, and nothing else, so a month is a grouped query over the index. Documents expire thirty-one days after they are written, one more than the longest window, so the container is its own retention policy (ADR: The App Service plan, read every minute).",
"indexingPolicy": {
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{ "path": "/kind/?" },
{ "path": "/day/?" },
{ "path": "/at/?" },
{ "path": "/b5/?" },
{ "path": "/h1/?" },
{ "path": "/h4/?" },
{ "path": "/cpu/?" },
{ "path": "/memory/?" },
{ "path": "/http_queue/?" }
],
"excludedPaths": [
{ "path": "/*" }
]
}
}
Live from infra/cosmos/plan.json, region *, read from this build at 99df7a8.
Two dials for the two numbers that run out. Processor and memory, as a ring each, read from the newest kept minute; the tab asks again every thirty seconds while it is open and the server caches its answer a minute, so the dials move once a minute. The ring carries the thresholds as marks on its inner edge, a gold dot at the thirty-day ninety-fifth percentile and a red dot at the thirty-day peak, so the reading has its history beside it. The dials answer the question the plan exists for: how much of the machine is left.
Deploys and platform events on the memory line. Every kept minute carries the build version the site was running, so the thirty-day chart draws a gold marker wherever the version changed, with no second source and no clock to reconcile. Azure's own events, read from the Activity Log, draw as red dashed lines on the same axis. This is the decision the whole card rests on: the two things that move memory are drawn where memory is drawn.
{}
{fullLines(chart.marks, window).map((mark) =>
mark.kind === 'deploy' ? (
<g key={`${mark.at_ms}-${mark.title}`} className={styles.deploy}>
<line x1={x(mark.at_ms)} x2={x(mark.at_ms)} y1={TOP} y2={TOP + plot} />
<path
d={`M ${x(mark.at_ms) - 3.5} ${TOP} L ${x(mark.at_ms) + 3.5} ${TOP} L ${x(mark.at_ms)} ${TOP + 6} Z`}
/>
<title>{mark.title}</title>
</g>
) : (
<line
key={`${mark.at_ms}-${mark.title}`}
className={styles.event}
x1={x(mark.at_ms)}
x2={x(mark.at_ms)}
y1={TOP}
y2={TOP + plot}
data-testid="cloud-event"
>
<title>{mark.title}</title>
</line>
)
)}
Live from src/components/admin/CloudChart/CloudPanel.tsx, region plan-markers, read from this build at 99df7a8.
Thresholds held by a test, sustained before they speak. Processor amber at 60 and red at 80 per cent, memory amber at 70 and red at 85, the HTTP queue amber at 5 and red at 20 waiting, outbound sockets amber at 60 per cent of the plan's 1,920. Each must hold for fifteen minutes before the card changes colour, so a deploy's two-minute warm-up spike reads as a spike and not as an alarm. Any app stopped, or any unplanned restart in the window, is red at once. PlanThresholdTests holds every number.
public static partial class PlanThresholds
{
public const int Sustained = 15;
public static readonly (double Amber, double Red) Cpu = (60, 80);
public static readonly (double Amber, double Red) Memory = (70, 85);
public static readonly (double Amber, double Red) HttpQueue = (5, 20);
public static int? SocketLimitFor(string? sku)
{
var size = SizeName().Match(sku?.Trim() ?? "");
if (!size.Success)
{
return null;
}
bool premium = size.Groups[1].Value.Equals("P", StringComparison.OrdinalIgnoreCase);
if (premium != size.Groups[3].Success)
{
return null;
}
int step = (size.Groups[2].Value[0] - '0') + (premium ? 1 : 0);
return step is >= 1 and <= 4 ? (1 << (10 + step)) - 128 : null;
}
[System.Text.RegularExpressions.GeneratedRegex("^([BSP])(\\d)(V3)?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)]
private static partial System.Text.RegularExpressions.Regex SizeName();
public const double SocketsAmberShare = 0.60;
public static PlanTone ToneOf(IReadOnlyList<double?> minutes, (double Amber, double Red) levels)
{
var last = minutes.TakeLast(Sustained).ToList();
if (last.Count < Sustained || last.Any(value => value is null))
{
return PlanTone.Info;
}
return last.All(value => value >= levels.Red) ? PlanTone.Alarm
: last.All(value => value >= levels.Amber) ? PlanTone.Warning
: PlanTone.Good;
}
public static PlanTone SocketsTone(IReadOnlyList<double?> minutes, int? limit) =>
limit is { } sockets ? ToneOf(minutes, (sockets * SocketsAmberShare, double.PositiveInfinity)) : PlanTone.Info;
public static PlanTone AppsTone(IReadOnlyList<PlanAppState> apps) =>
apps.Count == 0 ? PlanTone.Info
: apps.Any(app => !string.Equals(app.State, "Running", StringComparison.OrdinalIgnoreCase)) ? PlanTone.Alarm
: PlanTone.Good;
public static PlanTone EventsTone(IReadOnlyList<PlanEvent> events) =>
events.Any(e => e.Kind == "restart" && !e.Planned) ? PlanTone.Alarm
: events.Count > 0 ? PlanTone.Info
: PlanTone.Good;
}
Live from api/TheYard.Application/Shared/History/PlanThresholds.cs, region plan-thresholds, read from this build at 99df7a8.
Absent is a sentence, never a zero. No Reader role on the plan, no minute kept, a window with a gap: each is said in words on the card. A dial at zero would claim the machine is idle, and a flat line through a gap would claim nothing happened. The cost cards set this rule (ADR: What Azure charges) and the plan card keeps it.
Every resource name is a link to its portal blade. The plan and each app are drawn as links to portal.azure.com/#@{tenant}/resource/{resourceId}, with the tenant and the resource id taken from the Azure read, never typed. The link opens with the viewer's own Azure sign-in, which only the owner has, and the card says so beside it. A reader who cannot open the blade still sees the name, which is the point of naming it.
What this cost
A recorder, a reader, a container definition, and one Admin card in six parts. The containers' identity needs Reader on the plan and the three sites, which covers the metrics and the Activity Log, at no charge; it already held Reader on the resource group, which the plan and every site inherit, so no assignment was made. That was read back through the runner, and the screenshot is below with the container's. No new Azure resource and no tier change.
Alternatives
Read Azure Monitor from the page. Rejected: every visitor to the tab would cost a metrics call, the tab would wait on Azure, and a throttled read would leave the dials blank. The kept copy costs one write a minute whoever is looking.
Draw deploys from the deploy workflow's history. Rejected: that is a second source with its own clock, and the whole point of the chart is one clock. The version the site was running when the minute was kept is already true and already there.
Put the plan card under "Is it costing anything?" Rejected on the owner's ruling: the plan is infrastructure, and the cost of it is already on the cost card. A new section, Cloud infrastructure, holds this card and the two cards about the container that were under the cost question before.
Where it sits
PlanRecorder and PlanReader are in TheYard.Api beside the machines recorder, and they share its credential and its once-per-process rule. The port IPlanHistory is in TheYard.Application; CosmosPlanHistory in TheYard.Infrastructure.Cosmos is its only implementation. The card is src/components/admin/PlanCard, which chooses the route, drawn by parts split by job, each in a folder of its own as every component is (ADR: One folder per component): CloudDial, CloudChart, CloudRows, CloudReadout, framed by CloudCard (CardShell from 1.0.4.0, ADR: One frame for every resource, the addendum of 20 October). The thresholds sit in TheYard.Application beside the port, because they are a rule about the readings and not about Azure. Nothing in Domain knows the plan exists.
What would change it: a second resource read the same way, at which point the recorder and the container shape become one shared shape with the resource as its parameter. The card's parts were built shared from the start, so the frame is already the one the next record names.
Files
api/TheYard.Api/Shared/PlanReadings/PlanRecorder.cs - the minute's read and the hourly read
api/TheYard.Api/Shared/PlanReadings/PlanReader.cs - the reads from Azure Monitor and Resource Manager
api/TheYard.Api/Shared/PlanReadings/PlanView.cs and api/TheYard.Api/Shared/PlanReadings/PlanRows.cs - the windows, the percentiles, the markers, the rows
api/TheYard.Application/Shared/History/PlanThresholds.cs - every threshold and its hold time
api/TheYard.Application/Shared/Cards/CloudWire.cs - the records the wire carries
api/TheYard.Application/Shared/History/PlanHistory.cs - the port
api/TheYard.Infrastructure.Cosmos/Features/Admin/CosmosPlanHistory.cs - the keep
infra/cosmos/plan.json - the container, its key, its time to live, its index
api/TheYard.Tests/PlanViewTests.cs - fixed minutes in, fixed report out
api/TheYard.Tests/PlanThresholdTests.cs - the numbers above, held
src/components/admin/PlanCard/ - the card; its parts are CardShell, CloudDial, CloudChart, CloudRows and CloudReadout
src/lib/bench.ts - the Cloud infrastructure section
tests/e2e/cloud.spec.ts - the dials, the three apps and the section, on the page
Configuration, read back through the runner on 18 October: the identity's Reader on the resource group, which the plan and its apps inherit, and the plan container on the account.


The minute's path, Azure Monitor to recorder to Cosmos DB to card:

Addendum, 2026-10-18: a deploy is a span, and a spike inside one is a blip
The gold marker above says where the version changed; from 1.0.3.177 the chart also shades the whole roll. Every deploy writes each site's settings and then its image, and Azure's Activity Log, already read hourly, records both as configuration writes on the app; writes within ten minutes of each other are one roll, and the span runs from the first to three minutes after the last, while App Service starts the new container beside the old one and the plan runs both. The owner asked for it after the plan card's CPU sparkline showed two spikes: "I'd like to pull that data in so it's obvious it's just a blip." The "What did Azure do to it?" row now lists each roll in a table as a planned deploy with how long it took, and any spike over the amber line inside one is named in a sentence as the roll it was. Nothing about the fifteen-minute hold changes: a roll lasts about two minutes, so it could never turn a dial amber, and now the reason is on the chart.
public static class PlanDeploys
{
public static readonly TimeSpan SameRoll = TimeSpan.FromMinutes(10);
public static readonly TimeSpan Settle = TimeSpan.FromMinutes(3);
public static readonly TimeSpan NewBuildWithin = TimeSpan.FromMinutes(30);
public static IReadOnlyList<CloudBand> Rolls(IReadOnlyList<PlanEvent> events, IReadOnlyList<PlanBucket> buckets)
{
var writes = events.Where(e => e.Kind == "config").Select(e => e.At).Distinct().Order().ToList();
var bands = new List<CloudBand>();
int at = 0;
while (at < writes.Count)
{
var start = writes[at];
var last = start;
while (at + 1 < writes.Count && writes[at + 1] - last <= SameRoll)
{
last = writes[++at];
}
at++;
var end = last + Settle;
string? before = buckets.LastOrDefault(b => b.At < start && b.Version is not null)?.Version;
string? version = buckets.Where(b => b.At >= start && b.At <= start + NewBuildWithin)
.Select(b => b.Version)
.FirstOrDefault(v => v is not null && v != before)
?? buckets.FirstOrDefault(b => b.At >= start && b.Version is not null)?.Version;
string title = version is not null && before is not null && version != before
? $"Deploy {version}: a new container beside the old, then the swap"
: "A configuration change on the plan's apps";
bands.Add(new CloudBand(start.ToUnixTimeMilliseconds(), end.ToUnixTimeMilliseconds(), title));
}
return bands;
}
public static IReadOnlyList<string> Blips(IReadOnlyList<CloudBand> bands, IReadOnlyList<PlanBucket> buckets)
{
var said = new List<string>();
foreach (var band in bands)
{
var inside = buckets.Where(b => b.At.ToUnixTimeMilliseconds() >= band.StartMs - 300_000 && b.At.ToUnixTimeMilliseconds() <= band.EndMs).ToList();
double? cpu = inside.Max(b => b.CpuMaxPercent ?? b.CpuPercent);
double? memory = inside.Max(b => b.MemoryMaxPercent ?? b.MemoryPercent);
string when = DateTimeOffset.FromUnixTimeMilliseconds(band.StartMs).UtcDateTime.ToString("MMM d HH:mm", CultureInfo.InvariantCulture);
if (cpu >= PlanThresholds.Cpu.Amber)
{
said.Add($"CPU reached {cpu.Value.ToString("0", CultureInfo.InvariantCulture)} % in the roll at {when} UTC, a blip: the two containers overlapped for {Overlap(band)}");
}
else if (memory >= PlanThresholds.Memory.Amber)
{
said.Add($"memory reached {memory.Value.ToString("0", CultureInfo.InvariantCulture)} % in the roll at {when} UTC, a blip: the two containers overlapped for {Overlap(band)}");
}
}
return said;
}
public static string Overlap(CloudBand band)
{
int minutes = Math.Max(1, (int)Math.Round((band.EndMs - band.StartMs) / 60_000.0));
return minutes == 1 ? "1 minute" : $"{minutes} minutes";
}
public static string? KeptSince(IReadOnlyList<PlanBucket> buckets, DateTimeOffset windowStart, TimeSpan grain) =>
buckets.Count > 0 && buckets[0].At - windowStart > grain
? $"kept since {buckets[0].At.UtcDateTime.ToString("MMM d HH:mm", CultureInfo.InvariantCulture)} UTC"
: null;
}
Live from api/TheYard.Api/Shared/PlanReadings/PlanDeploys.cs, region plan-deploys, read from this build at 99df7a8.
Addendum, 2026-10-19: what each app holds and burns
Steve asked on 19 October for the four apps' RAM and CPU beside the plan's dial. The plan's kept minutes already carried each app's working set and its seconds of processor a minute, so nothing new is read: the table under "What does it power?" gains a Memory now and a CPU now column, the CPU as the app's seconds of processor over the sixty seconds each of the plan's cores had, and a last row for the plan's memory no app's working set accounts for, the operating system, the platform's containers beside each site and the file cache. Read the night it shipped, that last row was the largest thing on the plan: about 1.5 of the 2.45 GB in use, with the four apps' working sets at about 920 MB between them. PlanChildrenTests holds the arithmetic.
Addendum, 2026-10-19: what the last row is, and is not
The power table's last row, "the plan, outside the apps", is not a reading. No Azure metric names it. It is the plan's memory in use minus what every app reports for itself (PlanChildren.OutsideMb): the host's own Linux, the platform's agent, the image layers the plan keeps, and one Kudu sidecar beside each app. It read 1,603 MB at 13:46 UTC on 19 October against 977 MB for the four apps together, which is why the three .NET web apps became one (ADR: One web app for every .NET process). An hour after they did, the row read 1,613 MB: it did not follow the apps down, and the plan's saving, 72 to 61 per cent, came from the apps' own memory. What it is not: a measure of the operating system alone, or anything an app could give back by collecting its own garbage. Its second cell now says so on the row, "Linux and the platform (derived: plan memory used minus the apps)", and PlanViewTests holds the words.
Addendum, 2026-10-20: what the card reads instead of typing
From 1.0.3.194 the card holds no table of plan sizes. Until then PlanSizes mapped a size's name to its cores, its memory, its most instances and its storage, and PlanView.NextSize carried the next Basic size's price; each was a fact typed once and true only until Azure changed it. Now the most instances is the plan read's own maximumNumberOfWorkers, the cores and memory are what the recording process sees on the instance it runs on (MachineSize: the processors the runtime was given and the memory Linux states, the cgroup's limit when one is set, v2's memory.max or v1's memory.limit_in_bytes, and /proc/meminfo's total otherwise; from 1.0.3.197 and 1.0.4.5, before which it was the collector's figure, the heap cap), and the storage quota and the price are left off the card, because nothing this process reads states them. The line under the dials, the chart's dashed line and the size row's red mark are written from PlanThresholds, the same levels the tones use; the roll's sentence names how long the two containers overlapped as the roll's own band measured it; the empty-keep sentence names the recording site by its configured host; and the last row of the power table says Linux only when the plan read says so. The route asks one handler, ReadPlanHandler, over an IPlanCard port (ADR: The onion cut into vertical slices, rule 7). PlanViewTests, CloudReadersTests, PlanHandlerTests and PlanEndpointStatusTests hold it.
Addendum, 2026-10-21 (1.0.4.24): the socket limit follows the size
The "1,920" outbound sockets this record compares against is the B1 figure. Since 1.0.4.4 the card reads the limit for the plan's own size from the table in PlanThresholds (1,920, 3,968, 8,064 for Basic and Standard 1 to 3, and Premium v3's four), so on B2 the line is 3,968.
Addendum, 2026-11-11 (1.0.5.24): the plan's view is kept built
What stopped being true: the Decision says the server caches the plan's answer a minute. A 48-hour probe found that cache never answered: every one of about 280 reads of /api/admin/plan built the view, at a p95 of 7.9 to 13.7 s. From this version the plan's windows are kept the way the Cloud cards' are (ADR-102, the addendum of this version): a view under two minutes old answers at once, past one minute the next is built behind the request, and one keeper builds again each window asked for in the last hour, once a minute. The dials still move once a minute.
Enforced by
One rule in the rulebook cites this record, each held by a test on every release.