📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

Your design works, but finance says the projected Azure bill is too high. How do you treat cost as a design constraint? Walk me through how you estimate the monthly cost of a design from the capacity numbers, which components usually dominate, and the techniques you use to design the cost down without hurting reliability or security.

Cost as a system design constraint: estimating monthly Azure cost from capacity numbers, the usual cost drivers (compute, database, egress, telemetry, idle environments), design and commercial levers, unit economics, and FinOps practice.

Senior Architecture Advanced architecture azure capacity-estimation cost-optimisation finops system-design

๐ŸŽฏ Key points

  • Estimate cost from the capacity table: requests/s → instances, storage/year → GB-months, egress GB, telemetry GB, priced in the Azure pricing calculator for the target region on the day, with assumptions stated
  • Usual drivers: always-on compute, databases sized for peak, egress and cross-region traffic, log and telemetry ingestion, idle non-production environments
  • Express cost as unit economics (cost per 1,000 orders or per tenant per month) so it scales with the business
  • Design levers: autoscale and scale to zero, right-size the data store, cache to shrink the database tier, async to smooth peaks, tiered storage and retention
  • Efficient code is a cost lever: profile hot paths (allocations, N+1 queries, sync-over-async) so fewer replicas and a smaller DB tier carry the same load
  • Commercial levers: reservations and savings plans for steady base load, spot for interruptible batch, dev/test pricing, Azure Hybrid Benefit
  • Telemetry cost control: sampling, log levels, daily caps, cheaper log table plans, shorter retention; never cut reliability or security without pricing the risk
  • Make cost visible and keep optimising: tags, budgets and alerts in Azure Cost Management, Azure Advisor recommendations, cost in the ADR, a monthly review

โฑ 30-second answer

I treat cost like latency: an estimated, measured number in the design. From the capacity table I derive instance counts, database tier, storage GB-months, egress and telemetry volume, price them in the Azure pricing calculator with stated assumptions, and express the result as unit economics โ€” cost per 1,000 orders or per tenant per month. The usual drivers are always-on compute, a database sized for peak, log ingestion, cross-region traffic and idle non-production environments. Design levers: autoscale and scale to zero, cache to shrink the database, queues to flatten peaks, storage tiers and retention. Commercial levers: reservations or savings plans for the base, spot for batch. The trade-off: every saving costs something โ€” headroom, latency, resilience or engineering time โ€” so I price each against its reliability impact.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"I'd treat cost as a non-functional requirement with a number, not a surprise at the end. I take the capacity estimate โ€” say 300 requests a second average, 1,500 at peak, 2 TB of data growing 500 GB a year, 5 TB a month of egress โ€” and turn each line into a billable unit: instance-hours, database vCores, GB-months, GB of egress, GB of logs ingested. I price them in the Azure pricing calculator with my assumptions written down, and then I divide by a business unit, like cost per 1,000 orders or per tenant per month, because that's what finance can plan with.

In my experience the bill is dominated by a few predictable things: compute that's always on and sized for peak, a database tier chosen for the worst hour of the year, telemetry nobody samples, and non-production environments that run all weekend. For example, at [company] we [had an Azure bill of around $X a month where Application Insights ingestion was the second-largest line]. I [introduced sampling, moved verbose logs to a cheaper table plan and cut retention for debug data, and scheduled dev and test environments to shut down out of hours], [and the bill dropped about 35% with no change to our SLOs]. Then I'd look at design changes: caching to drop a database tier, a queue to flatten a peak so I don't provision for it, scale-to-zero for spiky workloads on Container Apps or Functions, and lifecycle policies to move old blobs to cool or archive.

The mistake I see is cutting cost by cutting redundancy โ€” dropping zone redundancy or backups to save a few hundred dollars โ€” without pricing the outage risk. Or the opposite, buying reservations before right-sizing, which locks in waste for a year or three. My order is: measure, remove waste, right-size, redesign the expensive parts, then commit with reservations for the steady base. Cost is a design constraint like any other, and the senior move is making the trade-off explicit."


From capacity to cost (illustrative)

Line Capacity input Billable unit Driver to check
API compute 1,500 req/s peak รท ~500 req/s per replica = 3 + 1 spare vCPU/GiB-seconds or instance-hours Peak vs average: autoscale or reserve the base
Database 300 writes/s, 2 TB vCores, storage GB, backup GB Sized for peak hour; can a cache drop a tier?
Cache 10 GB hot set Redis tier Often pays for itself by shrinking the DB
Storage +500 GB/year GB-month by tier, operations Lifecycle to cool/archive
Egress 5 TB/month GB out of Azure, cross-region CDN (Front Door) caching, keep traffic in region
Telemetry 50 GB/day logs GB ingested + retention Sampling, levels, table plans
Non-prod 3 environments Same as prod if cloned Smaller SKUs, shut down out of hours

Unit prices change and vary by region and agreement, so I always price with the Azure pricing calculator for Australia East at the time and quote the assumptions rather than memorised numbers.

Levers

Lever Typical saving Risk / cost When not to
Remove idle / orphaned resources 5โ€“15% Very low Never a reason not to
Right-size (CPU, DB tier) 10โ€“30% Less headroom Just before a known peak
Autoscale / scale to zero High for spiky loads Cold starts Latency-critical steady loads
Reservations / savings plans Up to roughly half off pay-as-you-go for steady base 1โ€“3 year commitment Before right-sizing
Spot VMs Large discounts for interruptible work Eviction Stateful or user-facing
Telemetry sampling and retention Often large Less detail in rare cases Audit logs you must keep
Caching Lets DB drop a tier Staleness, invalidation Strongly consistent reads

Production example

A [SaaS] platform costing [$31k] by shutting down non-production overnight and at weekends ([-12%]), sampling and re-tiering telemetry ([-9%]), adding Redis so Azure SQL could drop from [16 to 8 vCores] ([-8%]), and buying a savings plan for the steady compute base ([-6%]). SLO attainment stayed at [99.96%].

๐Ÿ” What the interviewer is checking

Checks whether the candidate can estimate and reduce the running cost of a design with the same rigour as performance and reliability, without trading away safety blindly.

Green flags

  • Derives cost from the capacity estimate with stated assumptions and the pricing calculator
  • Names the real drivers: always-on compute, DB sized for peak, telemetry, egress, non-prod
  • Uses unit economics and FinOps practice (tags, budgets, reviews)
  • Orders levers: remove waste, right-size, redesign, then commit

Red flags

  • Quotes memorised prices as facts
  • Cuts redundancy or security without discussing risk
  • "Move to serverless" as the only answer

๐Ÿ“š Learn in depth

1. Cost is a function of the design

cost = ฮฃ (units consumed ร— unit price)
units consumed = f(traffic, data, retention, redundancy, environments)

Every design choice changes a term: zone redundancy multiplies some resources, a cache trades Redis cost for database cost, a CDN trades Front Door cost for egress and origin compute.

2. Peak vs average

load
 ^        peak (1,500 req/s, 2 h/day)
 |       /\
 |  ____/  \____     average 300 req/s
 +---------------------> time

Provisioning for peak all day pays for idle capacity ~90% of the time. Options: autoscale (Container Apps, App Service, AKS HPA/KEDA), queue-based load levelling (accept work quickly, process at a steady rate), or reserve the base and pay-as-you-go for the burst.

3. Hidden lines

  • Egress and cross-region traffic: replication between regions, clients downloading large files, chatty calls across regions.
  • Telemetry: Log Analytics charges by GB ingested; verbose logs at Information level in hot paths add up fast. Use sampling in OpenTelemetry/Application Insights, LogLevel filtering, daily caps, and cheaper table plans for low-value logs.
  • Per-operation charges: storage transactions, Key Vault operations, Cosmos DB RUs for poorly indexed queries.
  • Non-production: full-size clones of production running 24ร—7.

4. Unit economics

Total monthly cost tells you little; cost per business unit tells you whether the design scales. If cost per 1,000 orders rises as volume grows, something is super-linear (a fan-out, a cross-partition query, an unsampled log). Track it monthly.

5. FinOps loop

  1. Inform: tag every resource (env, team, product), Azure Cost Management views, budgets with alerts.
  2. Optimise: Azure Advisor recommendations, right-sizing, reservations after a stable baseline.
  3. Operate: cost in design reviews and ADRs, a monthly review with engineering and finance.

6. Cost vs reliability vs security

Never trade away backups, zone redundancy for critical stores, or security controls (WAF, private endpoints, Defender) without pricing the risk: expected outage cost = probability ร— impact. A $300/month saving that adds a 1% annual chance of a $500k outage is a bad deal.

7. Try it yourself

  1. Take a design and fill in the capacity-to-cost table with the Azure pricing calculator for Australia East.
  2. In Azure Cost Management, group last month's cost by service and by tag; find the top three lines.
  3. Run a KQL query on Log Analytics Usage to find which tables ingest the most data.
  4. Turn on sampling in a test app's OpenTelemetry setup and compare ingested volume before and after.
  5. Compute cost per 1,000 requests for two months and explain the difference.

๐Ÿ’ป Code

Two cheap, high-impact changes in a .NET 10 service: sampled telemetry and log levels that keep noisy categories out of paid ingestion.

using Azure.Monitor.OpenTelemetry.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

// Azure Monitor OpenTelemetry distro: sample traces instead of sending every request.
// 0.2 keeps 20% of traces; errors still show up in metrics, which are not sampled.
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
    o.SamplingRatio = 0.2f;
});

// Keep chatty framework categories out of paid log ingestion.
builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);

var app = builder.Build();
app.MapGet("/health", () => Results.Ok());
app.Run();

Finding the biggest telemetry cost in Log Analytics:

Usage
| where TimeGenerated > ago(30d) and IsBillable == true
| summarize IngestedGB = sum(Quantity) / 1024 by DataType
| order by IngestedGB desc

A scale-to-zero worker in Azure Container Apps (Bicep excerpt): replicas follow queue length instead of running all day.

scale: {
  minReplicas: 0
  maxReplicas: 20
  rules: [
    {
      name: 'orders-queue'
      custom: {
        type: 'azure-servicebus'
        metadata: { queueName: 'orders', messageCount: '50' }
        identity: 'system'
      }
    }
  ]
}

โš  Common mistakes

  • Mistake: Leaving cost until after go-live. Why it is wrong: Expensive choices (database model, regions, telemetry volume) are hard to undo later. Instead: Estimate cost from the capacity table in the design and record it in the ADR.
  • Mistake: Quoting prices from memory or from another region. Why it is wrong: Unit prices change often and differ by region; Australia East is usually dearer than US regions, and Australia Southeast may lack some SKUs. Instead: Price in the Azure pricing calculator for the actual region on the day, and write the date and assumptions next to the estimate.
  • Mistake: Sizing everything for peak, all day. Why it is wrong: You pay for idle capacity most of the time. Instead: Autoscale, scale to zero where cold starts are acceptable, or level load with a queue.
  • Mistake: Buying reservations before right-sizing. Why it is wrong: It locks in waste for one to three years. Instead: Measure and right-size first, then reserve the steady base.
  • Mistake: Scaling out to hide inefficient code. Why it is wrong: N+1 queries, heavy allocations and sync-over-async multiply replicas and database load, and you pay for them every hour. Instead: Profile with dotnet-trace, dotnet-counters and Query Store, fix the hot path, then right-size.
  • Mistake: Ignoring telemetry cost. Why it is wrong: Unsampled traces and verbose logs can be one of the largest lines. Instead: Sample traces, filter log levels, use cheaper table plans and set retention per table.
  • Mistake: Forgetting egress and cross-region traffic. Why it is wrong: Large downloads and chatty cross-region calls are billed per GB and grow with users. Instead: Cache at the edge, keep traffic in one region, compress responses.
  • Mistake: Running non-production at production size 24ร—7. Why it is wrong: It can double the bill for little value. Instead: Smaller SKUs, dev/test pricing, scheduled shutdowns, ephemeral environments per pull request.
  • Mistake: Cutting redundancy, backups or security controls to save money. Why it is wrong: The expected cost of an outage or breach is usually far larger than the saving. Instead: Price each cut against its risk and keep the controls the SLO and compliance need.
  • Mistake: Treating optimisation as a one-off project. Why it is wrong: Usage drifts and new resources appear; savings erode within months. Instead: Review Azure Advisor cost recommendations and Cost Management anomalies monthly, and track unit cost (per order, per tenant).

๐Ÿ› Senior insight: trade-offs

Seniors make cost visible and comparable: a number in the design, a unit cost the business understands, and tags so the bill maps to teams and products. The best savings come from design (fewer always-on resources, smaller hot data, less telemetry noise) rather than haggling over SKUs, and the worst ones come from quietly removing resilience. Measure with Azure Cost Management and Advisor, and review it monthly like any other SLO.

Option When it fits Cost / risk When not to
Serverless / scale to zero (Functions Flex Consumption, Container Apps) Spiky or low traffic, background work Cold starts, per-execution pricing at high volume Steady high load (reserved compute is cheaper)
Reserved / savings plan Steady base load known for 1โ€“3 years Commitment Unstable or shrinking workloads
Cache to shrink DB Read-heavy with tolerable staleness Redis cost, invalidation Write-heavy, strongly consistent reads
Tiered storage and retention Data rarely read after N days Retrieval latency and fees Frequently accessed data
Multi-region Business needs regional resilience Roughly 2ร— infrastructure When zone redundancy meets the SLO

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate compares App Service, Functions, Container Apps or AKS Why: Checks they can choose the compute platform with cost and operations in mind
    How to answer

    I choose by how much platform the team wants to run:

    • App Service: one or a few web apps, always on, deployment slots, almost no ops. Paid per plan instance.
    • Azure Functions: event-driven or spiky work (queues, timers, blobs); Flex Consumption scales per event and to zero.
    • Container Apps: containerised microservices on managed Kubernetes with KEDA scaling, revisions and scale to zero, without touching the cluster.
    • AKS: full Kubernetes when you need its API, custom networking or many services and have a platform team.

    The trade-off is control versus operations: each step towards AKS gives more control and more work. I start with the simplest option that meets the requirements and move only when I hit a concrete limit.

  2. When: Candidate mentions telemetry or metrics cost Why: Checks they can find and fix a real observability cost blow-out
    How to answer

    Cardinality is the number of unique label combinations; each is a separate time series. A user_id label multiplies a metric's series by the number of active users, and on a histogram that is again multiplied by every bucket, so 20 routes ร— 5 status codes ร— 17 buckets ร— 50,000 users is 85 million series.

    I confirm it with prometheus_tsdb_head_series (or the Azure Monitor workspace's active series and ingestion metrics), find the metric with topk(10, count by (__name__) ({__name__=~".+"})), and the label with count(count by (user_id) (...)). I stop the bleeding without a deploy by dropping the label in the OpenTelemetry Collector or with Prometheus labeldrop, then remove the tag in code and move per-user questions to traces and logs.

    The trade-off: per-user detail is real value, but metrics are the wrong place for unbounded data.

  3. When: Candidate starts from capacity numbers Why: Checks they can produce the estimate the cost model depends on
    How to answer

    A capacity estimate turns user numbers into load. Start with daily active users ร— actions per user to get requests per day, divide by ~86,400 s (round to 10^5) for average requests/s, then multiply by a peak factor (2โ€“10ร—, often 3ร—). For storage, multiply writes per day by record size and 365, then add indexes and replicas. For bandwidth, multiply requests/s by payload size.

    Example: 10M DAU ร— 20 reads = 200M reads/day โ‰ˆ 2,300/s average, ~7,000/s peak.

    The point is not precision โ€” it's deciding whether one database and a cache are enough or you need partitioning. The trade-off is speed versus accuracy: round hard, but state every assumption.

๐Ÿ›  Real-world problems: how you handle them

Cutting a SaaS Azure bill by a third without touching the SLO
Situation
[B2B SaaS] on Azure Australia East costing [~$48k AUD] a month, growing [6%] month on month while revenue grew [3%]; finance asked for a [25%] reduction.
Signals
Cost per tenant rising each month; Application Insights in the top three cost lines; dev, test and UAT environments at production size running 24×7; Azure SQL averaging [30%] CPU.
Investigation
Grouped Azure Cost Management by service and tag; queried Log Analytics `Usage` for top tables; reviewed Azure Advisor right-sizing; load tested the API with Redis in front of the catalogue to check whether the database could drop a tier.
Resolution
Immediately scheduled non-production shutdowns out of hours and deleted orphaned disks and IPs. Then enabled trace sampling and moved verbose logs to a cheaper table plan, added Redis so Azure SQL could drop from [16 to 8 vCores], and bought a savings plan for the steady compute base.
Prevention
Mandatory tags enforced by Azure Policy, budgets with alerts per product, cost per tenant on the team dashboard, a cost section in every ADR and a monthly FinOps review.

How to tell it (STAR)

**S:** Our [SaaS] Azure bill was growing faster than revenue, and finance asked for a [25%] cut. **T:** I had to find savings without hurting reliability. **A:** I broke the bill down by service and tag, shut non-production down out of hours, sampled and re-tiered telemetry, added a cache so the database could drop a tier, and only then committed to a savings plan for the steady base. **R:** The bill fell from [~$48k] to [~$31k] a month, a [35%] cut, and SLO attainment stayed at [99.96%].

More in Senior Design Focus

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me