DOTNET Contents

.NET / ASP.NET Core

C# and ASP.NET Core are powerful tools for building modern web APIs and services. Learn production ready patterns and architecture.

111 lessons · 0 examples

Foundations (Hosting, DI, Config)(7)

Web Services Basics (ASP.NET Core)(7)

Controllers vs Minimal APIs (Tradeoffs in Prod)
Choose Controllers vs Minimal APIs based on production constraints: versioning, validation, filters, authz, observability, and how the wrong choice creates messy incidents and broken contracts.
Middleware Pipeline Order (Bugs You Deserve)
Middleware order is production behavior. Get it wrong and you will leak data, break auth, lose correlation, and turn outages into mysteries. Learn the correct pipeline and failure modes.
Routing Basics (Endpoints That Bite)
Routing is the front door of your service. Learn endpoint matching, route constraints, ambiguity traps, and production-safe patterns for versioning, auth, and observability.
Endpoint Filters Basics
Endpoint filters let you enforce cross-cutting policies for Minimal APIs (validation, authz prechecks, logging, idempotency). Used well they prevent drift; used poorly they add hidden complexity.
Request/Response Streaming (Backpressure Matters)
Streaming changes your reliability model. Learn request/response streaming, backpressure, cancellation, buffering traps, and how incorrect streaming causes OOM, timeouts, and partial responses.
Static Files (Security Foot-guns)
Static files are a security boundary. Learn safe hosting, path traversal risks, cache headers, content-type sniffing, and how misconfigured static files leak secrets or enable XSS.
Shutdown Draining (Don't Drop In-Flight)
Draining is how you stop taking traffic before shutdown. Learn readiness flipping, connection draining, load balancer behavior, and how bad draining creates deploy-time outages.

Routing, Binding & Validation(6)

Errors & Problem Details (RFC 7807)(6)

Authentication & Authorization(7)

Cookie vs Bearer Auth (Don't Mix Blindly)
Cookies and Bearer tokens solve different production problems. Learn threat models, CSRF vs token theft, SameSite pitfalls, mobile/API use cases, and how the wrong choice creates security incidents.
JWT Validation Basics (What Actually Matters)
JWT validation is not “check signature and done”. Learn issuer/audience rules, clock skew, alg traps, claim normalization, replay risks, and how bad validation becomes a production breach.
JWT Key Rotation & kid Handling
JWT key rotation and kid handling must be seamless and strict. Learn how to support multiple signing keys safely, avoid downtime during rotation, and prevent accepting malicious keys.
AuthZ Policies, Roles, Claims
Authorization is more than roles. Learn how to design policies using roles and claims safely, avoid over-trusting tokens, and prevent privilege escalation in production.
Resource-Based Authorization
Resource-based authorization is how you prevent horizontal privilege escalation. Learn per-resource checks, tenant boundaries, and how to enforce ownership without leaking existence or creating N+1 auth calls.
ASP.NET Identity: When to Use It
ASP.NET Core Identity is powerful but heavy. Learn when to use it, when not to, how it impacts scaling, and how misuse leads to auth complexity and production incidents.
mTLS Client Certs (Basics)
mTLS adds strong client authentication at the transport layer. Learn how to use client certificates safely, validate chains and revocation, and avoid false trust in production.

Security Basics (Production)(10)

CORS Misconfigurations (Real Impact)
CORS is a browser policy, not an API security control. Learn common misconfigurations that leak data, enable credential abuse, and create production-only failures.
Security Headers (Baseline)
Security headers reduce exploitability: clickjacking, XSS, content sniffing, referrer leaks, and transport downgrade. Learn a production-safe baseline and rollout strategy without breaking apps.
CSRF: SameSite vs Token Defenses
CSRF is about unwanted state-changing requests in browsers. Learn the difference between SameSite and anti-forgery tokens, why CORS is not enough, and how to defend cookie-based apps correctly.
XSS: Output Encoding & HTML Safety
XSS is usually your bug, not the framework’s. Learn output encoding rules, Razor safety boundaries, JSON injection pitfalls, and how a single unsafe render turns into account takeover.
Deserialization Hardening
Deserialization is an attack surface. Learn how unsafe model binding, polymorphism, over-posting, and large payloads turn into privilege escalation or DoS in production.
SSRF & Egress Controls
SSRF turns your API into a proxy to internal networks. Learn how outbound HTTP calls become attack vectors and how to enforce egress controls, DNS/IP validation, and safe HttpClient usage.
Rate Limiting Basics (Server-Side)
Rate limiting protects availability and fairness. Learn how to apply per-IP, per-user, and per-endpoint limits correctly, avoid self-DoS, and monitor abuse without breaking legitimate traffic.
Request Size Limits (Abuse Prevention)
Request size limits prevent memory exhaustion and slow-body attacks. Learn how to enforce limits at Kestrel, reverse proxy, and endpoint level without breaking legitimate uploads.
Secrets Management for .NET Apps
Secrets are not config values. Learn how to manage connection strings, API keys, and signing secrets securely using environment isolation, secret stores, and rotation strategies.
Dependency Vulnerability Scanning
Dependency vulnerabilities are supply-chain risk. Learn how to scan NuGet packages, enforce upgrade policies, avoid blind auto-updates, and prevent vulnerable libraries from reaching production.

Data Access (EF Core in Prod)(9)

DbContext Lifetime & Pooling (Prod-Safe)
DbContext lifetime and pooling are not style choices. Wrong scope or blind pooling causes memory spikes, stale state, thread contention, and cross-request data leaks. This is how you set it up for real traffic and real incidents.
Migrations Safe Rollout (No Downtime)
Migrations are deployments. Unsafe rollout will lock tables, block writes, and take down your API. This covers zero-downtime patterns: expand/contract, backfill, and operational guards.
Transactions & Isolation Levels
Transactions are where reliability goes to die: hidden ambient transactions, wrong isolation, and long locks. Learn how to pick isolation levels, diagnose blocking, and keep transactions short and safe.
N+1 Detection & Fix
N+1 is a silent latency tax that turns into an outage at scale. Detect it with logs and traces, fix it with projection, includes, split queries, and data shaping that does not torch memory.
Query Performance & Index Reality
EF Core performance is mostly SQL performance. If you do not measure query plans and indexes, you are guessing. This covers slow query triage, indexes, projection, compiled queries, and how to avoid self-inflicted scans.
Optimistic Concurrency Tokens
Concurrency in EF Core is not optional when you scale writes. Without tokens you will silently overwrite data. With tokens you can detect conflicts, return correct errors, and avoid rage-retry storms.
Outbox Pattern (Basics)
If you publish events from the same DB write, you need the outbox. Otherwise you will lose messages, double-send, or ship inconsistent state. This is the minimal outbox for EF Core.
Soft Delete & Global Query Filters
Soft delete is easy to add and hard to operate. Global filters can hide data, break admin tools, and leak cross-tenant reads if you get it wrong. Do it with explicit bypass rules and indexes.
Connection Resiliency (Retries Without Lies)
Connection resiliency is not "turn on retries". Wrong retries duplicate writes and turn outages into data corruption. Do transient retries only where safe, use idempotency, and bound the blast radius.

HTTP Clients & Integrations(7)

HttpClientFactory: Pooling & DNS Reality
HttpClientFactory fixes the classic socket exhaustion trap, but it does not magically make outbound HTTP safe. This covers handler pooling, DNS refresh, lifetime tuning, and how to stop stale IPs and connection storms from taking your service down.
Timeouts & Deadlines (Stop Hanging Threads)
Timeouts are not optional. Without explicit time budgets, hung upstream calls will pile up, exhaust thread pool, and cascade into a full outage. This covers per-request deadlines, connect timeouts, and cancellation wiring end-to-end.
Retries & Backoff Policies (When It's Okay)
Retries are a correctness feature, not a resilience toggle. Blind retries duplicate writes, amplify load, and turn partial outages into full outages. This covers backoff, jitter, per-status policies, and bounded retry budgets.
Circuit Breakers (Basics That Matter)
Circuit breakers prevent retry storms from turning a degraded dependency into a platform-wide outage. Use them to fail fast, shed load, and recover cleanly, with clear thresholds and observability.
Idempotency Keys for Outbound Calls
Idempotency keys are how you retry writes without corrupting data. If you retry POST without a key, you will eventually double charge, double create, or double send. This covers key design, server enforcement, and operational reality.
Headers/Auth Forwarding (Don't Leak)
Headers are a security boundary. Blindly forwarding Authorization, Cookie, or X-Forwarded-* is how you leak tokens, break multi-tenant isolation, and create SSRF-like pivots. This covers safe header propagation and auth patterns for integrations.
HTTP/2 and HTTP/3 Considerations
HTTP/2 and HTTP/3 change failure modes: multiplexing, head-of-line behavior, connection coalescing, and proxy compatibility. If you do not test and tune, you will see weird latency spikes and integration failures in production.

Reliability Patterns(8)

Timeouts & CancellationTokens (Correct Wiring)
Timeouts and CancellationTokens are your first line of defense against slow dependencies. If you do not enforce time budgets end-to-end, requests will pile up, thread pools will starve, and your service will collapse under perfectly normal traffic.
Retries: When NOT To (Thundering Herd)
Retries can improve success rate for transient failures, or they can multiply load, duplicate side effects, and turn minor incidents into major outages. You need strict rules for when to retry and when to stop.
Idempotency for APIs (You Need This)
Idempotency in APIs is how you survive retries, client disconnects, and unknown commit states without corrupting data. Without it, you will double-create, double-charge, or double-send. This is the server-side playbook.
Server-Side Rate Limiting (Fairness & Abuse)
Server-side rate limiting is not about being nice. It is about survival: protecting CPU, memory, thread pool, and downstream dependencies. Done wrong, it blocks legitimate traffic and still lets abuse through.
Bulkheads & Concurrency Limits
Bulkheads and concurrency limits stop one hot dependency from consuming all resources. Without them, a slow downstream call will saturate threads, sockets, and memory, and unrelated endpoints will die with it.
Backpressure in Streaming (Don't OOM)
Backpressure is how you avoid buffering yourself into an OOM. If your service streams data or processes queues, you must control how fast producers can push and how slow consumers can pull. Otherwise memory becomes your queue.
Graceful Degradation & Fallbacks
Graceful degradation is not hiding errors. It is controlled failure: returning partial responses, using stale-but-safe cache, and protecting core flows when dependencies are down. The goal is to keep the product usable.
Saga & Compensation (Basics)
Sagas and compensation are how you build multi-step workflows without distributed transactions. The goal is not perfection; it is controlled consistency with explicit failure handling, retries, and compensating actions.

Background Jobs & Hosting(6)

HostedService Basics (The Safe Way)
IHostedService is not a free background thread. If you run background work inside your web app without lifecycle discipline, you will lose jobs on deploy, create duplicate runs across replicas, and ship silent failure. This is the production-safe baseline
Background Queue with Channels
In-memory background queues are fine until you treat them like durable infrastructure. A Channel-based queue can control backpressure and concurrency, but it will drop work on crash unless you persist. This is the safe pattern for in-process queues.
Cron Scheduling: Hangfire vs Built-in
Cron scheduling in production is about coordination, durability, and operations. In-process timers are easy and fragile. Hangfire adds persistence and dashboards but changes your failure modes. This compares patterns and how they blow up.
Worker Service Deploy Patterns
Worker Service deployments fail differently than web apps: missed signals, hard kills, no drain, and invisible backlog. This is how to deploy, observe, and scale .NET workers without losing work or melting downstreams.
Message Consumers & Idempotency
Message consumers are at-least-once by default. If your consumer is not idempotent, you will eventually double-process and corrupt data. This is the practical idempotency playbook for .NET consumers.
Shutdown: Cancellation & Job Draining
Shutdown is a feature. If your app cannot drain in-flight work, deploys and scale-downs will lose jobs and create duplicates. This covers cancellation, draining, stop intake, and the hard truth about forced kills.

Observability (Logs, Metrics, Traces)(8)

Structured Logging with Serilog
Serilog is not a fancy Console.WriteLine. In production, structured logs are your incident timeline: you need stable event shapes, minimal noise, and enough context to answer “what broke, where, and why” without leaking secrets.
Correlation IDs & Trace Context
Correlation is how you turn 500 microservices into one story. If you do not propagate TraceContext and correlation IDs end-to-end, you will waste hours during incidents and still not know which dependency caused the blast.
OpenTelemetry Tracing (ASP.NET Core)
OpenTelemetry tracing is how you stop guessing. It gives you per-request dependency graphs, latency breakdowns, and failure localization. Done wrong, it becomes noise and cost. This is the production setup and the traps.
OpenTelemetry Metrics (SLI-first)
Metrics are how you detect incidents before users scream. OpenTelemetry metrics give you request rates, error rates, and latency distributions, but the real value is dependency and backlog metrics that map to SLOs.
Health Checks Deep Dive (Readiness Done Right)
Health checks are not a ping endpoint. Readiness must reflect dependency ability, liveness must reflect process correctness, and deep checks must not DOS your own database. This is how to do health in production without lying.
Log PII Redaction (Don't Get Sued)
PII in logs is a security incident in slow motion. Redaction is not “hide the password field” — it is systematic control over what can leave the process via logs, traces, and exception messages.
Alerting & SLO Basics (Actionable Only)
Alerting without SLOs is just noise. SLO-driven alerting tells you when users are hurt and keeps pages actionable. This is the pragmatic baseline: define SLIs, set error budgets, and wire alerts that do not cry wolf.
Debugging in Prod (Dumps, Traces)
When production is on fire, dumps are the truth. If you cannot take a dump safely and analyze it, you are blind to deadlocks, thread pool starvation, and memory leaks. This is the incident playbook for .NET dumps.

Performance & Tuning(7)

ThreadPool Starvation (Symptoms & Fix)
ThreadPool starvation is the most common “service is alive but dead” failure mode in ASP.NET Core. It happens when you block threads on I/O or sync-over-async, and under load it turns into a full outage with low CPU and infinite latency.
Async Pitfalls (Deadlocks, Fire-and-Forget)
Async code fails in production in predictable ways: fire-and-forget, missing cancellation, deadlocks via sync waits, and accidental parallelism. These are the patterns that create outages, data corruption, and impossible debugging.
Allocations & GC (What Actually Hurts)
Most .NET performance problems are allocation problems. If you allocate per request without discipline, GC becomes your hidden tax, tail latency spikes, and throughput collapses. This is the incident-driven GC and allocation baseline.
Kestrel Tuning & Limits
Kestrel tuning is about protecting the server under abusive or broken clients: connection limits, request body limits, header limits, keep-alive, and timeouts. Without sane limits, one client can pin resources and cause a platform-wide outage.
JSON Serialization Performance
JSON serialization is often your top CPU and allocation hotspot. The usual killers are reflection-based serialization, per-request options allocation, string-heavy DOM usage, and large payload buffering. This is how to make JSON fast and safe.
EF Core Perf Hotspots (How to See Them)
EF Core performance failures are usually self-inflicted: N+1 queries, cartesian explosions, tracking overhead, missing indexes, and chatty SaveChanges. The fix is disciplined query shape, tracking control, and database-first observability.
Caching: Response/Output Strategies
Caching is not “store it somewhere”. Response/output caching can cut latency and cost, or it can serve the wrong data to the wrong user and become a security incident. This covers safe cache keys, invalidation, and production guardrails.

Testing & Quality Gates(7)

Unit Testing with xUnit (Basics)
xUnit unit tests are not about “green checkmarks”. They are a safety net for pure logic and edge cases that will absolutely blow up in prod: time boundaries, nullability, parsing, and invariants. Keep them fast, deterministic, and ruthless.
Integration Tests with WebApplicationFactory
WebApplicationFactory integration tests are where you catch real breakage: routing, DI, auth, serialization, middleware order, and database wiring. If you skip this, you will ship “works locally” incidents to production.
Contract Tests (Basics)
Contract tests stop “we changed JSON and didn’t tell anyone” outages. They verify provider/consumer expectations with automated checks so you catch breaking changes in CI, not after a deploy.
Mocking HTTP and Time Safely
Mocking is where tests go to die: brittle setups, time-based flakiness, and fake HTTP that doesn’t match reality. Mock responsibly: mock boundaries, control time deterministically, and avoid overfitting to implementation.
Testcontainers Basics (Real Dependencies)
Testcontainers gives you real dependencies (Postgres, Redis, RabbitMQ) in CI without shared staging flakiness. Use it to catch config, migrations, and query issues before production—while keeping tests isolated and repeatable.
Coverage & Quality Gates (No Theatre)
Coverage is not quality, but quality gates are survival. Use coverage thresholds as a blunt tool, then add smarter gates: mutation-like expectations, critical path coverage, and “no known risk” checks that block unsafe merges.
Load Testing with k6 (Basics)
Load testing with k6 is how you find the real failure modes: timeouts, queue buildup, saturation, and meltdown thresholds. Do it before production does it for you. Focus on scenarios, budgets, and abort conditions—not vanity RPS.

Build, Release & Deploy(8)

Build/Publish, Trimming, AOT (Basics)
Publish options (trim/AOT) can cut size and cold start, or they can ship a runtime landmine: missing reflection types, broken serializers, and impossible-to-debug production crashes. Treat trimming/AOT as a compatibility project, not a flag.
Dockerizing ASP.NET Core (Production)
Dockerizing ASP.NET is not “FROM mcr.microsoft.com/dotnet/aspnet”. Production containers need non-root, deterministic builds, fast startup, correct port binding, and aggressive size control without breaking diagnostics.
Config & Secrets in Deploy (No Baking)
Config and secrets deployment is where teams accidentally leak credentials, restart-loop on missing env vars, or ship unsafe defaults. Production config must be validated at startup, rotated safely, and never stored in images or repos.
Blue/Green & Canary (Basics)
Blue/green and canary are not buzzwords; they are blast-radius control. Without staged rollouts, every deploy is a full-production experiment. Canary gives you fast signal, green gives you fast rollback, and both need hard metrics gates.
Migrations & Deploy Order (Avoid Locking)
Deploy order around migrations is where outages are born. If you deploy app code that expects schema changes before the DB is ready, you crash. If you apply destructive migrations before old code is gone, you break older pods. You need backward/forward co
Rollbacks vs Forward-Fix (When Each Wins)
Rollbacks are not a strategy unless they are fast, safe, and rehearsed. Many incidents cannot be rolled back because migrations are destructive or data is already written in the new format. Learn when to roll back and when to forward-fix.
Versioning & SemVer (APIs Included)
SemVer in backend services is not cosmetic. It is how you communicate breakage risk, control deployments, and version contracts. If you don’t version intentionally, clients will treat every release as a gamble.
CI/CD Basics (Build, Test, Scan, Ship)
CI/CD is your production safety system: repeatable builds, deterministic tests, security scanning, and controlled rollouts. If your pipeline can’t guarantee what was built and deployed, you don’t have “delivery” — you have chaos.

Production Runbooks(8)

Incident Triage Playbook (First 15 Minutes)
When prod is on fire you don’t “investigate”. You triage: stop the bleeding, find the failure domain, and pick the fastest safe mitigation. This playbook is the default sequence to reduce MTTR under pressure.
Dependency Outage Playbook (Third-Party Down)
Dependency outages are inevitable. Your job is to fail fast, protect your core, and degrade gracefully. This playbook covers how to detect upstream failure, stop retry storms, and keep your service useful under partial failure.
DB Latency Playbook (EF Core Included)
DB latency is a service killer. The right response is not “scale app”. You must reduce DB work, stop expensive queries, and protect the pool. This playbook is the shortest path from DB pain to stable service.
Memory Leak Playbook (OOM Hunting)
Memory leaks don’t look like bugs; they look like “random” OOMs after hours or days. This playbook shows how to confirm a leak, capture the right evidence, and stop the bleeding without guessing.
CPU Saturation Playbook (Hot Paths)
CPU saturation is not “add more cores”. It’s usually one hot path: serialization, crypto, regex, LINQ, or a runaway loop. This playbook finds the hotspot fast and applies safe mitigations without making the incident worse.
Timeout Storm Playbook (Cascading Failure)
Timeout storms are self-inflicted avalanches: one slow dependency triggers retries, saturates pools, and spreads failure across the system. This playbook stops the storm by cutting time budgets, killing retries, and isolating the blast radius.
Deploy Failure Playbook (Rollback Safely)
Deploy failures are usually predictable: bad config, broken migrations, image pull issues, readiness lies, or crash loops. This playbook gets you from “pods won’t come up” to a safe rollback/forward-fix fast.
Production Readiness Checklist
Production readiness is not “it runs”. It is proving the service will survive failure: timeouts, retries, deploys, scale events, dependency outages, and abuse. This checklist is the minimum bar before you ship.