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

📚 Interview question

How do you build security and observability into a system design from the start rather than bolting them on later? In a design interview, what do you say about trust boundaries, identity, data protection and privacy, and about logs, metrics, traces and SLOs?

Security and observability as first-class design concerns: trust boundaries, identity between services, encryption and secrets, privacy and data residency, plus logs, metrics, traces, SLOs and alerts designed alongside the architecture.

Mid-Level Theory Intermediate observability opentelemetry privacy security-by-design system-design threat-modelling

🎯 Key points

  • Draw trust boundaries on the diagram: internet, edge, app tier, data tier, third parties
  • Authenticate users at the edge (Entra ID / OIDC) and services with managed identities, no shared secrets
  • Encrypt in transit (TLS 1.2 minimum, TLS 1.3 preferred) and at rest; secrets in Key Vault; private endpoints for data stores
  • Least privilege for each workload identity: scoped Azure RBAC and database roles, not db_owner
  • Classify data and apply the Australian Privacy Principles (collection, use, APP 8 cross-border, APP 11 security), NDB scheme and residency
  • Observability by design: OpenTelemetry traces, metrics and structured logs with a shared trace id
  • Define SLIs and SLOs for the key user journeys and alert on symptoms (burn rate)
  • Keep it continuous: threat model per new data flow, Defender for Cloud and Azure Policy for automated posture checks, tamper-evident audit log

⏱ 30-second answer

I treat security and observability as parts of the diagram, not footnotes.

For security I draw trust boundaries, then say how each crossing is protected: users authenticate at the edge with Entra ID / OIDC, services use managed identities, data stores sit behind private endpoints, secrets live in Key Vault, and personal data is classified, minimised and kept in Australia East for Privacy Act obligations.

For observability I add OpenTelemetry traces, metrics and structured logs with one trace id across services, define SLOs for the main user journeys, and alert on burn rate, not CPU.

The trade-off is upfront effort and some cost (private networking, telemetry ingestion) against far cheaper incidents and audits later.

🗣 Full answer (senior)

How I would answer this in an interview

"Once I have the high-level diagram, I do one pass for security and one for observability, because both are much cheaper to design in than to retrofit. For security I draw the trust boundaries: the internet, the edge, the app tier, the data tier and any third party. Every arrow that crosses a boundary needs an answer to 'who is calling, how do we know, and what can they do'. Users authenticate at the edge with OpenID Connect against Entra ID or Entra External ID; services authenticate to each other and to Azure resources with managed identities, so there are no connection-string passwords to leak. Data stores get private endpoints and no public access, secrets go in Key Vault, and everything is TLS in transit and encrypted at rest.

Then privacy: what personal information do we hold, do we need it, who can see it, and where does it live? For an Australian system, the Privacy Act and APP 11 mean reasonable steps to protect it, and a breach may be notifiable under the NDB scheme, so I minimise what's stored, keep it in Australia East with backups in Southeast, and mask it in logs. If there's time I do a quick STRIDE pass on the riskiest flow.

For observability I design the telemetry with the services: OpenTelemetry for traces, metrics and logs, exported to Application Insights or a Grafana stack, with W3C trace context flowing through HTTP calls and Service Bus messages so one trace id follows a request end to end. I define SLIs for the key journeys — 'checkout succeeds within 2 seconds' — set SLOs, and alert on burn rate. The mistake I see is 'we'll add logging later', which really means the first incident is investigated blind."


Security checklist on the diagram

Boundary / concern Design decision Azure / .NET
Internet → edge WAF, DDoS protection, TLS Front Door + WAF
User identity OIDC, MFA, short-lived tokens Entra ID / External ID, AddJwtBearer
Service → service / resource Workload identity, least privilege Managed identity, Azure RBAC
App → data Private network, no public endpoint Private endpoints, VNet integration
Secrets and keys Central, rotated, audited Key Vault
Personal data Classify, minimise, mask, residency Australia East/Southeast, redaction
Security events Tamper-evident audit trail Separate Log Analytics workspace, immutable storage

Observability checklist

Signal What it answers .NET
Traces Where did this request spend time and fail? OpenTelemetry, ActivitySource
Metrics Is the service healthy right now? (RED) System.Diagnostics.Metrics
Logs What exactly happened? ILogger structured logging
SLOs Are users getting what we promised? SLI queries + burn-rate alerts
Health checks Can this instance serve traffic? AddHealthChecks
[Internet] --TLS--> | Front Door + WAF | --> | App (managed identity) | --private endpoint--> | Azure SQL |
   trust boundary 1          boundary 2                  boundary 3               
                     \___________ OpenTelemetry (trace id) ___________/--> Application Insights

Production example

A team that designed telemetry in from day one — trace ids through Service Bus, RED metrics per endpoint and a checkout SLO of 99.5% under 2 s — found a slow third-party address lookup within 6 minutes of the first alert, because the trace showed 1.8 s in one dependency span. A sister team without tracing took most of a day to find a similar problem.

🔍 What the interviewer is checking

Checks whether the candidate treats security and observability as structural parts of a design and can name concrete mechanisms for each.

Green flags

  • Draws trust boundaries and protects each crossing
  • Managed identities, private endpoints, Key Vault without prompting
  • Mentions privacy obligations and data residency
  • Designs traces with propagation through queues and defines SLOs

Red flags

  • "We'll add security and logging later"
  • Shared secrets or public database endpoints
  • Observability means "we'll log errors"

📚 Learn in depth

1. Why retrofitting is expensive

Security and telemetry touch every component. Adding managed identity after go-live means rotating every connection string; adding private endpoints means network redesign and downtime; adding trace propagation means changing every client and consumer. Designing them in costs a few boxes on the diagram and a few lines in Program.cs.

2. Trust boundaries

A trust boundary is where data or control passes between parts with different privileges. Threats concentrate there: spoofed callers, tampered messages, leaked data.

  untrusted          semi-trusted            trusted
  [browser] ---> [edge / gateway] ---> [services] ---> [data stores]
                 authN, WAF, rate       authZ,          private network,
                 limits                 validation      encryption, RBAC

STRIDE gives a checklist per crossing: Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege.

3. Identity everywhere

Users get tokens from an identity provider; APIs validate signature, issuer, audience and expiry. Services use managed identities: Azure issues the token, so the app holds no secret. DefaultAzureCredential picks it up in Azure and uses developer credentials locally. Authorisation is least privilege: the order service's identity can read and write its own database and send to one queue, nothing more.

4. Privacy as a design input

Classify data (public, internal, confidential, sensitive). Under the Privacy Act 1988, APP 11 requires reasonable steps to protect personal information and to destroy or de-identify it when no longer needed; APP 8 covers cross-border disclosure. Design consequences: data minimisation, retention policies, encryption, residency in Australian regions, masking in logs and access auditing.

5. Observability as a design input

The three signals share context. OpenTelemetry in .NET builds on Activity (traces), Meter (metrics) and ILogger (logs); ASP.NET Core and HttpClient emit spans automatically, and the trace id is attached to log records. Messaging needs explicit propagation of traceparent in message properties. SLOs turn telemetry into decisions: an error budget tells you when to stop shipping features and fix reliability.

6. Costs

Private endpoints, WAF and telemetry ingestion all cost money. Sampling traces, setting log levels and retention by data class keep telemetry affordable without losing errors.

Try it yourself

  1. Draw trust boundaries on a system you know and list how each crossing is authenticated.
  2. Replace a SQL connection string password with managed identity using Authentication=Active Directory Default.
  3. Add OpenTelemetry to two ASP.NET Core services and confirm one trace spans both in Application Insights or Jaeger.
  4. Write a KQL query that computes a success-rate SLI for one endpoint over 28 days.
  5. Run a 20-minute STRIDE session on one data flow and record three threats and mitigations.

💻 Code

Security and observability wired in at start-up: JWT validation, managed identity to Azure SQL with least-privilege roles, and OpenTelemetry exporting to Azure Monitor.

// Program.cs — .NET 10
using Azure.Monitor.OpenTelemetry.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Users: tokens from Entra ID, validated for issuer, audience, lifetime and signature.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = builder.Configuration["Auth:Authority"];
        o.Audience = builder.Configuration["Auth:Audience"];
    });
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("orders:write", p => p.RequireClaim("scp", "orders.write"));

// Data: no password in the connection string; the app's managed identity is used.
// e.g. "Server=tcp:shop.database.windows.net;Database=shop;Authentication=Active Directory Default;"
builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));

// Telemetry: traces, metrics and logs via the Azure Monitor OpenTelemetry distro.
builder.Services.AddOpenTelemetry().UseAzureMonitor();

builder.Services.AddHealthChecks().AddDbContextCheck<ShopDb>(tags: ["ready"]);

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapPost("/orders", (CreateOrder cmd, ILogger<Program> log) =>
{
    // Structured log without personal data; the trace id is attached automatically.
    log.LogInformation("Order received for {ItemCount} items", cmd.Items.Count);
    return Results.Accepted();
}).RequireAuthorization("orders:write");

app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });
app.Run();

public sealed record CreateOrder(IReadOnlyList<string> Items);
public sealed class ShopDb(DbContextOptions<ShopDb> options) : DbContext(options);

Least privilege in the database for the app's managed identity (run once by an Entra admin of the server):

-- The user name is the managed identity's (or app's) name in Entra ID.
CREATE USER [shop-api] FROM EXTERNAL PROVIDER;

-- Read and write data only: no DDL, no db_owner.
ALTER ROLE db_datareader ADD MEMBER [shop-api];
ALTER ROLE db_datawriter ADD MEMBER [shop-api];

-- Narrower still: allow executing only the stored procedures in one schema.
GRANT EXECUTE ON SCHEMA::orders TO [shop-api];
-- Migrations run from the pipeline under a separate identity with DDL rights.

⚠ Common mistakes

  • Mistake: Leaving security to a later phase. Why it is wrong: Identity, networking and data residency are structural; changing them after go-live means migrations and downtime. Instead: Put trust boundaries, identity and network isolation on the first diagram.
  • Mistake: Shared secrets between services. Why it is wrong: Passwords and keys in config leak through repos, logs and screenshots and are rarely rotated. Instead: Managed identities and Azure RBAC; Key Vault for anything that must remain a secret.
  • Mistake: Giving the app's identity broad rights. Why it is wrong: A compromised service with db_owner or subscription Contributor can read or destroy everything. Instead: Grant the managed identity only the database roles and RBAC scopes it needs.
  • Mistake: Public endpoints on databases and storage. Why it is wrong: They widen the attack surface to the whole internet. Instead: Private endpoints and disabled public network access.
  • Mistake: Logging identifiable personal data by default. Why it is wrong: Logs are copied widely, kept long and accessed by many people, so they break data minimisation and multiply the impact of any breach. Instead: Log opaque ids rather than names, emails or addresses, redact sensitive fields, and restrict and time-limit access to log workspaces.
  • Mistake: Treating logs as observability. Why it is wrong: Logs alone can't show where a request spent time across services or whether users are meeting the SLO. Instead: Traces, metrics and logs correlated by trace id, plus SLOs.
  • Mistake: Alerting on CPU and memory. Why it is wrong: Causes are noisy and often harmless; users care about symptoms. Instead: Alert on SLO burn rate and error rate for user journeys.
  • Mistake: Treating security as a one-off review. Why it is wrong: New features add data flows and drift appears in configuration. Instead: Threat-model each new flow, enforce rules with Azure Policy, and watch Defender for Cloud recommendations continuously.

🏛 Senior insight: trade-offs

Seniors frame both concerns as risk and cost. Security spend goes where the impact is highest: the internet edge, identity and the data stores holding personal information. Observability spend goes to the user journeys that matter, with sampling and retention tuned so telemetry doesn't become the biggest line on the bill. They also know what the platform gives for free — ASP.NET Core and HttpClient instrumentation, the Azure Monitor distro, Defender for Cloud recommendations — and spend their effort on the gaps.

Option When it fits Cost When not to
Private endpoints everywhere Personal or regulated data Network complexity, DNS Throwaway prototypes
Managed identity Any Azure-hosted service Little Cross-cloud callers (use workload identity federation)
Full tracing, 100% sampling Low volume, early stages Ingestion cost grows with traffic High volume: sample, keep errors
SLO-based alerting User-facing services Needs good SLIs Batch jobs (alert on freshness instead)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions STRIDE or threat modelling Why: Checks whether they can run a threat model inside normal delivery
    How to answer

    Threat modelling is a structured way to find design-level security flaws before you write the code. I answer four questions: what are we building, what can go wrong, what will we do about it, and did we do a good job? I draw a data flow diagram (processes, data stores, external entities and flows) and mark the trust boundaries, because that is where most threats live. Then I walk each element with STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege. Each threat becomes a decision (mitigate, accept, transfer or eliminate) and mitigations become backlog items with acceptance criteria. I do it at design time and whenever a change adds or crosses a trust boundary. The trade-off is depth against cadence: a 60-minute session every feature beats a two-day workshop nobody repeats.

  2. When: Candidate mentions managed identities or least privilege Why: Checks practical least-privilege design on Azure
    How to answer

    Least privilege means every identity gets only the permissions it needs, at the smallest scope, for the shortest time. For a .NET service in Azure I give each workload its own managed identity and assign data-plane roles at resource scope: Storage Blob Data Reader on one container, Key Vault Secrets User on one vault, never Contributor on the subscription. In Azure SQL the app is a contained user with read/write or object-level grants, not db_owner; migrations run under a separate identity in the pipeline. Humans have no standing admin rights: they elevate through Entra PIM, time-bound and audited. That maps to the Essential Eight's restrict administrative privileges strategy. The trade-off is operational friction: narrow scopes mean more role assignments and more "access denied" during development, so you codify them in Bicep or Terraform rather than clicking in the portal.

  3. When: Candidate mentions SLOs or burn-rate alerts Why: Checks how they design alerting that people act on
    How to answer

    Alert on symptoms users feel, such as the request error-rate or latency SLI, failed synthetic journeys or orders per minute dropping, because causes like CPU at 80% often hurt nobody and miss failures with no resource signal at all. The best symptom alert is SLO burn rate: how fast you are spending the error budget. With a 99.9% SLO, a 14.4× burn over 1 hour (confirmed over 5 minutes) spends 2% of a 30-day budget and pages; 6× over 6 hours pages; slower burns raise a ticket.

    Every alert needs who gets paged (the owning team's rotation), the threshold and window, a severity that decides page versus ticket, a dashboard link and a runbook with the first mitigation steps. Cause metrics stay on dashboards for diagnosis. The trade-off: fewer pages means a slightly later warning for slow-building problems, which tickets cover.

🛠 Real-world problems: how you handle them

Retrofitting private networking and managed identity after a security review
Situation
[Company]'s [customer portal] on Azure held personal information for [n] customers. It went live with public endpoints on Azure SQL and Blob Storage and connection-string passwords in app settings.
Signals
An external penetration test and Defender for Cloud flagged public data endpoints and secrets in configuration; an [audit / customer due-diligence questionnaire] required private networking and evidence of least privilege.
Investigation
Mapped every data flow and trust boundary; inventoried secrets in app settings and pipelines; used Azure Resource Graph and Defender for Cloud recommendations to list publicly reachable resources.
Resolution
Immediate: restricted firewall rules to known outbound IPs and rotated the exposed passwords. Then moved to managed identities for SQL, Storage and Service Bus, added private endpoints with private DNS zones, and disabled public network access, in [phases] with slot swaps to avoid downtime.
Prevention
Azure Policy denying public network access on data services; a design template with a mandatory trust-boundary diagram and data classification; secret scanning in the pipeline; threat model reviewed for each new data flow.

How to tell it (STAR)

**S:** At [company], our [customer portal] had gone live with public database endpoints and passwords in app settings, and a pen test flagged both. **T:** I was asked to fix it without downtime and stop it recurring. **A:** I mapped the trust boundaries and secrets, locked down firewalls and rotated passwords on day one, then moved every service to managed identity and private endpoints over [n] weeks using slot swaps. I added Azure Policy to block public endpoints and a trust-boundary section to our design template. **R:** We passed the [audit] with [no / n] findings, removed [n] secrets from configuration, and new services have shipped private by default since.

↩ Usually asked after

More in Core System Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me