CURRICULUM PREVIEWRevision 1 · Open for reviewReview the full course
THE WHOLE PICTURE

.NET Developer & Architect
One continuous read.

Every lesson, example, exercise, and answer in roadmap order. Use the contents to jump to a topic, or open any lesson on its own.

Revision 153 lessonsdraft
Developer

Build the foundation

C#, dependency wiring, HTTP, data, and tests.

CONNECTING THE PIECES8 min read

C# with a purpose

Model a booking with values, invariants, and clear ownership.

The idea

A booking reserves one seat for a tenant. Represent the identity as an immutable value and reject an empty tenant before persistence. A record is useful for data with value equality; it does not automatically enforce business rules. Keep rule checks close to the operation that needs them.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
public sealed record Booking(Guid Id, string TenantId);

static Booking CreateBooking(string tenantId)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(tenantId);
    return new Booking(Guid.NewGuid(), tenantId);
}

Decisions that matter

  • An immutable record makes updates deliberate; its referenced objects may still be mutable.
  • Keep transport validation and domain invariants distinct: both protect different boundaries.
  • Use explicit constructors or factory methods when a value must always be valid.

Your turn

Add a seat count and reject a value below one. What behavior should a test assert instead of checking the exact generated ID?

Reveal a worked answer

Assert that invalid counts are rejected and a valid booking retains the tenant and count. Check that the ID is nonempty and unique across calls; avoid binding the test to a randomly generated literal.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Async, await, and cancellation

Let I/O wait without occupying a request thread.

Before you begincsharp-foundations

The idea

An asynchronous database call allows the server to use a thread for other work while it waits. It does not make a slow SQL query fast. Propagate a CancellationToken from the request through the application boundary so abandoned work can stop at cooperative cancellation points.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
app.MapGet("/bookings/{id:guid}", async (
    Guid id, IBookingStore store, CancellationToken ct) =>
{
    var booking = await store.FindAsync(id, ct);
    return booking is null
        ? Results.NotFound()
        : Results.Ok(booking);
});

Decisions that matter

  • Await asynchronous I/O end to end; blocking on Result or Wait can exhaust request threads.
  • Cancellation is cooperative and does not imply that a committed write was undone.
  • Set operation deadlines and distinguish cancellation from application failures.

Your turn

A client cancels while the store is waiting on PostgreSQL. Where should the token travel, and why is Task.Run around the query unnecessary?

Reveal a worked answer

Pass the request token into the application operation and database API. Asynchronous I/O already yields while waiting; Task.Run adds scheduling overhead without improving the query. Test cancellation with a controlled fake that observes the token.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Dependency injection and lifetimes

Make the object graph explain your boundaries.

Before you begincsharp-foundations

The idea

The composition root is where implementations are selected. The booking use case depends on a store contract, while the host chooses a PostgreSQL adapter. Scoped services are usually tied to a request in ASP.NET Core. A singleton must not capture a scoped dependency.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
builder.Services.AddScoped<IBookingStore, PgBookingStore>();
builder.Services.AddScoped<CreateBooking>();
// Register a thread-safe shared cache as singleton only
// when its dependencies have compatible lifetimes.
Go
store := NewPgBookingStore(pool)
create := NewCreateBooking(store)
// Go wiring is explicit: construct dependencies at startup.

Decisions that matter

  • Constructor injection makes required collaborators visible.
  • A container resolves dependencies; it does not choose good module boundaries for you.
  • Keep service location out of domain code so dependencies remain testable.

Your turn

A singleton report service receives a scoped DbContext in its constructor. Identify the lifetime bug and choose a repair.

Reveal a worked answer

The singleton outlives the request scope and may share a non-thread-safe context. Make the report operation scoped, or create a scope deliberately for each background unit of work. Do not make the context a singleton.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Configuration without secret sprawl

Separate deploy-time settings from application behavior.

Before you begindependency-injection

The idea

A connection string belongs to the deployment environment, not a repository. Bind related settings into an options type and validate them at startup. Decide which values can reload safely; a database pool created once does not automatically follow a later settings change.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
builder.Services.AddOptions<BookingOptions>()
    .BindConfiguration("Bookings")
    .Validate(o => o.MaxSeats > 0, "MaxSeats must be positive")
    .ValidateOnStart();

public sealed class BookingOptions
{
    public int MaxSeats { get; init; } = 8;
}

Decisions that matter

  • Environment variables work well for deployment overrides; use a protected secret store for credentials.
  • Validate settings once at startup and again when reloadable values change.
  • Do not expose all effective settings through a public diagnostic endpoint.

Your turn

The production MaxSeats value is zero. When should this be detected, and what information is safe to log?

Reveal a worked answer

Fail startup validation before accepting traffic. Log the option name and failed rule, but exclude connection strings, tokens, and other secrets. Cover valid and invalid option sets in tests.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Middleware as a request pipeline

Place cross-cutting behavior in a deliberate order.

Before you beginconfiguration

The idea

Middleware wraps the next component and can short-circuit a request. An exception handler placed outside authentication, authorization, and endpoints can translate their failures. Authentication establishes identity; authorization evaluates permission. Order changes observable behavior.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
app.UseExceptionHandler("/error");
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/bookings", ListBookings)
   .RequireAuthorization("booking:read");

Decisions that matter

  • Middleware is appropriate for request-wide behavior, not hidden domain decisions.
  • A short-circuit must still return a documented status and response shape.
  • Test the order using anonymous, forbidden, successful, and throwing endpoints.

Your turn

Where would you add a correlation ID and how would you avoid trusting an unbounded incoming header?

Reveal a worked answer

Add correlation handling near the start so later logs can include it. Validate the supplied header length and allowed characters, or generate an ID. Return a consistent ID to the caller without putting user-controlled data into log message templates.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Controllers and minimal APIs

Choose an endpoint shape without moving business rules into it.

The idea

A controller groups related actions; a minimal API makes a small endpoint concise. Either should translate HTTP into a use-case call and translate the result back. Keep tenant selection, validation, and error semantics explicit regardless of the routing style.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
app.MapPost("/bookings", async (
    CreateBookingRequest input, CreateBooking useCase,
    CancellationToken ct) =>
{
    var result = await useCase.ExecuteAsync(input, ct);
    return Results.Created($"/bookings/{result.Id}", result);
});

Decisions that matter

  • Thin endpoints allow the same use case to be invoked by HTTP or a background job.
  • Route constraints reject malformed route values but do not replace business validation.
  • Choose one consistent error contract and test its status, body, and content type.

Your turn

Document the response when creation succeeds, the input is invalid, or the caller lacks access to the tenant.

Reveal a worked answer

Use 201 with a resource location on success, a documented validation response for invalid input, and 401 or 403 according to authentication and authorization outcomes. Enforce tenant permission in the application boundary rather than trusting a submitted tenant ID.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

OpenAPI as a tested contract

Describe the interface consumers can rely on.

Before you beginhttp-endpoints

The idea

An API description is valuable when it matches runtime behavior. Document the booking request, successful response, validation error, authentication scheme, and conflict cases. Review generated OpenAPI changes with the same care as code changes: removing a response property can break clients.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
builder.Services.AddOpenApi();
// Map the document only in the intended environment.
if (app.Environment.IsDevelopment())
    app.MapOpenApi();

app.MapGet("/bookings/{id:guid}", GetBooking)
   .Produces<BookingResponse>(200)
   .Produces(404);

Decisions that matter

  • Specification generation documents known metadata; it does not prove the implementation conforms.
  • Keep internal administrative endpoints out of a public document when required.
  • Pin the toolchain used to generate clients for repeatable builds.

Your turn

A generated client expects a 200 response, but the endpoint starts returning 204. What checks would catch the change?

Reveal a worked answer

Diff the generated specification, exercise the endpoint in a contract test, and compile or run a representative consumer. Decide whether the new status is a compatible change before releasing it.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

EF Core and query boundaries

Make database work visible before optimizing it.

Before you beginopenapi

The idea

An IQueryable describes work that may not have executed yet. Filter by tenant before materializing results and project only the fields needed by the response. A read-only view often does not need tracking. Observe query counts so a loop cannot quietly become an N+1 query pattern.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
var rows = await db.Bookings
    .AsNoTracking()
    .Where(b => b.TenantId == tenantId)
    .OrderBy(b => b.Id)
    .Select(b => new BookingResponse(b.Id, b.Seats))
    .Take(50)
    .ToListAsync(ct);

Decisions that matter

  • Projection reduces transferred data and avoids unintentionally exposing persistence entities.
  • Pagination requires a deterministic order; a unique tie-breaker prevents unstable pages.
  • Use a real database integration test for SQL translation and provider behavior.

Your turn

A booking list loads its tenant separately for each of 50 rows. How would you prove and remove the extra round trips?

Reveal a worked answer

Record database commands in an integration test and inspect the generated SQL. Project the required tenant fields in one query or load a bounded batch. Verify tenant isolation and returned ordering after changing the query.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Migrations with a rollback story

Treat schema evolution as part of the release.

Before you beginef-core

The idea

Schema changes and application versions can overlap during deployment. For a new required field, first add a compatible nullable column, deploy code that writes it, backfill existing rows, and only then enforce the constraint. Run migrations with a dedicated identity; the web app should not own the schema.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Expand: add nullable booking_reference
Deploy: write booking_reference for new rows
Backfill: fill existing rows in bounded batches
Verify: check missing and duplicate values
Contract: enforce NOT NULL and uniqueness

Decisions that matter

  • Prefer forward-compatible changes during rolling deployments.
  • A migration transaction does not make every large backfill cheap or nonblocking.
  • Record backup evidence, expected locks, and a tested recovery procedure.

Your turn

Why is dropping the old column in the same deployment risky, even if the new code no longer uses it?

Reveal a worked answer

An old process may still be serving traffic and a binary rollback may need the column. Wait until all supported versions have stopped reading it and the recovery window has closed. Test restoration from a backup rather than assuming a down migration recovers data.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Transactions and concurrency

Keep the invariant true when requests overlap.

Before you beginef-core

The idea

Two clients can both observe one seat available. A read followed by an unguarded write can oversell. Move the invariant into an atomic database operation or choose an isolation and locking strategy that protects it. A local transaction cannot atomically include an arbitrary external payment service.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
UPDATE seats
SET remaining = remaining - 1
WHERE event_id = $1 AND remaining > 0
RETURNING event_id;

-- No returned row means the reservation did not succeed.

Decisions that matter

  • Database constraints are the final defense for data invariants.
  • Long transactions hold locks and can reduce concurrency.
  • Retries need a bounded policy and must not duplicate committed side effects.

Your turn

Run two simultaneous reservations against the final seat. What result and final state must hold?

Reveal a worked answer

Exactly one reservation succeeds, remaining becomes zero, and the other caller receives a documented unavailable or conflict result. Use separate database connections in the test and assert committed state, not just returned values.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

A useful testing portfolio

Choose tests by the failure they can reveal.

Before you begintransactions

The idea

Unit tests isolate booking rules. Integration tests verify SQL, migrations, and dependency wiring. HTTP tests verify routes, authorization, and response contracts. A fake repository cannot prove PostgreSQL constraints work, and a large browser suite is a slow place to discover a small rule error.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void RejectsInvalidSeatCount(int seats)
{
    Assert.Throws<ArgumentOutOfRangeException>(
        () => Booking.Create("tenant-a", seats));
}

Decisions that matter

  • Use deterministic inputs and explicit time providers where time affects behavior.
  • Test externally visible behavior rather than private implementation details.
  • A small set of real boundary tests protects the assumptions fakes cannot model.

Your turn

Create a test plan for a tenant-scoped booking lookup with a PostgreSQL adapter.

Reveal a worked answer

Unit-test rule and error mapping. Integration-test the tenant predicate and missing row with PostgreSQL. HTTP-test anonymous access, a caller from another tenant, a valid caller, malformed IDs, and the successful response contract.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Authentication and authorization in .NET

Establish identity, then check the resource.

Before you begintesting

The idea

A valid token identifies a principal, but it does not grant access to every booking. Validate the issuer, audience, signature, and lifetime using the platform authentication handler. Apply coarse endpoint policies and a tenant-scoped resource check. Derive tenant membership from trusted identity and data, not a free-form header.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
builder.Services.AddAuthorization(options =>
    options.AddPolicy("booking:read", policy =>
        policy.RequireAuthenticatedUser()
              .RequireClaim("permission", "booking:read")));

// The query still includes the caller's authorized tenant.
app.MapGet("/bookings/{id:guid}", GetBooking)
   .RequireAuthorization("booking:read");

Decisions that matter

  • Prefer established identity middleware over a hand-built token validator.
  • Cookie-authenticated state changes need CSRF protection.
  • Recheck authorization for each object operation, including exports and background actions.

Your turn

A user with booking:read requests a booking ID from a different tenant. Why is the endpoint policy insufficient?

Reveal a worked answer

The claim authorizes the operation category, not ownership of the requested record. Scope the query to an authorized tenant and test that cross-tenant IDs reveal no booking data. Use a consistent missing/forbidden policy to limit enumeration.

Keep exploring

Open this lesson
CHECKPOINT8 min read

Logs, health, and deployment

Make a release observable and recoverable.

Before you begindotnet-auth

The idea

Use structured events for a booking operation, with a correlation ID, duration, and stable outcome. Keep secrets and personal data out of logs. Liveness answers whether the process is alive; readiness answers whether it can serve its required dependencies. Deployment is complete when the external route works and a recovery path exists.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
logger.LogInformation(
    "Booking operation {Operation} ended with {Outcome}",
    "create", outcome);

app.MapHealthChecks("/health/ready");

Decisions that matter

  • Do not turn raw exception messages into public error responses.
  • Separate operational metadata from sensitive request content.
  • An active systemd service proves process supervision, not the full user path.

Your turn

The process is running but its database credentials are wrong. What should readiness report, and what release evidence should you collect?

Reveal a worked answer

Readiness should fail without printing credentials. Verify the service, local health response, reverse proxy, DNS, TLS, and a representative authorized operation. Keep the previous binary and restore instructions available before shifting traffic.

Keep exploring

Open this lesson
Architect

Think in systems

Patterns with a problem, a trade-off, and a reason to exist.

CONNECTING THE PIECES10 min read

Modular monoliths

Keep one deployment while giving features real boundaries.

Before you beginlogging-deployment

The problem and the pattern

A small team needs independent booking and billing models without operating a fleet of services. Organize modules around business capabilities, expose narrow contracts, and keep tables under module ownership. Enforce references so the billing module cannot reach into booking internals.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
public interface IBookingModule
{
    Task<BookingReceipt> ReserveAsync(
        ReserveBooking command, CancellationToken ct);
}
// Billing consumes the public contract, not booking tables.

Trade-offs

  • One deployment simplifies releases and local debugging.
  • Boundaries still need automated dependency checks.
  • A shared database is compatible with module ownership; cross-module SQL is a policy decision.

When to avoid it

Avoid using folders as evidence of modularity when the team cannot enforce data and dependency boundaries.

Your turn

Draw the allowed dependencies for booking and billing. Where should a shared customer ID live?

Reveal a worked answer

Treat the ID as a value passed across contracts. Keep customer behavior in its owning module; avoid a shared model library that makes every module depend on every change.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Layered architecture

Give presentation, application, domain, and persistence distinct jobs.

Before you beginmodular-monolith

The problem and the pattern

An endpoint should translate HTTP, a use case should coordinate an operation, and the domain should decide booking rules. Layers reduce the number of places a change must be understood. Keep dependencies pointed toward stable rules rather than letting transport types become domain inputs.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
public sealed class ReserveBooking
{
    private readonly IBookingStore store;
    public ReserveBooking(IBookingStore store) => this.store = store;
    // Validate intent, apply rules, persist, then return a result.
}

Trade-offs

  • A layer can clarify ownership but adds navigation overhead.
  • Layering does not require a pass-through class for every method.
  • Test allowed dependency directions in the build.

When to avoid it

Avoid ceremonial layers that only forward arguments and provide no independent responsibility.

Your turn

A domain method returns an IActionResult. What boundary has leaked?

Reveal a worked answer

The domain depends on the web transport. Return a domain result or error and let the endpoint choose its HTTP representation.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Clean architecture

Keep business policies independent of infrastructure.

Before you beginlayered-architecture

The problem and the pattern

The booking rule should not know which database or HTTP framework hosts it. Define required persistence operations inside the application boundary and implement them outside it. The composition root is allowed to know both sides so it can assemble the application.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
public interface IBookingStore
{
    Task SaveAsync(Booking booking, CancellationToken ct);
}
// Domain and application projects do not reference EF Core.

Trade-offs

  • Dependency inversion makes adapters replaceable.
  • Mapping between transport, application, and storage models costs code.
  • Protect business rules first; do not add abstractions solely for hypothetical replacements.

When to avoid it

Avoid elaborate project splits in a small CRUD service when they obscure simple behavior without protecting rules.

Your turn

Which project owns IBookingStore, and why?

Reveal a worked answer

The application owns the contract because it describes what the use case needs. The infrastructure project implements it and references the application, reversing the usual dependency on storage details.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Hexagonal ports and adapters

Build one booking use case in C# and Go.

Before you beginclean-architecture

The problem and the pattern

A port describes a conversation with the application. An inbound adapter translates HTTP into a reservation command. An outbound port lets the use case save a booking without knowing PostgreSQL. C# commonly wires this through DI; Go commonly wires constructors explicitly. The business use case is the same.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
public interface IBookingStore
{
    Task SaveAsync(Booking booking, CancellationToken ct);
}
public sealed class Reserve(IBookingStore store)
{
    public Task ExecuteAsync(Booking booking, CancellationToken ct)
        => store.SaveAsync(booking, ct);
}
Go
type BookingStore interface {
    Save(context.Context, Booking) error
}
type Reserve struct { store BookingStore }
func (r Reserve) Execute(ctx context.Context, b Booking) error {
    return r.store.Save(ctx, b)
}
// reserve := Reserve{store: NewPgStore(pool)}

Trade-offs

  • Ports should reflect operations the application needs.
  • A single adapter does not make an interface mandatory.
  • Keep cancellation and errors meaningful across the boundary.

When to avoid it

Avoid exposing an entire ORM through a port: it leaks infrastructure and defeats the boundary.

Your turn

Replace the PostgreSQL adapter with a fake that records the booking. Which application code needs to change?

Reveal a worked answer

The composition root chooses the fake; the use case remains unchanged. Assert the saved booking and error propagation. Keep an integration test for the real adapter so the fake cannot conceal SQL bugs.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

DDD and bounded contexts

Let a model mean one thing inside a clear boundary.

Before you beginports-adapters

The problem and the pattern

Booking calls a customer the person holding seats. Billing calls a customer the account responsible for payment. These concepts share an identifier but have different rules and lifecycles. A bounded context names where a language and model apply; translation makes the boundary explicit.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
public sealed record BookingCustomer(string CustomerId);
public sealed record BillingAccount(
    string CustomerId, string Currency, bool CreditApproved);

Trade-offs

  • Context boundaries follow business meaning, not database table count.
  • Eventual consistency may be needed between contexts.
  • An anti-corruption layer prevents an external model from taking over local rules.

When to avoid it

Avoid deep tactical DDD machinery when the domain is straightforward data entry with little business complexity.

Your turn

A team proposes one shared Customer entity for booking and billing. What changes would expose the coupling?

Reveal a worked answer

A billing credit rule or currency requirement would force booking to understand billing behavior. Keep each context model focused and translate identifiers and facts at their integration boundary.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Microservices and service boundaries

Trade local calls for independent ownership deliberately.

Before you beginddd-contexts

The problem and the pattern

Separating booking and billing can let teams deploy independently. It also introduces network failures, distributed tracing, versioned contracts, and asynchronous consistency. Start a service boundary around a cohesive capability with a clear owner and an operational reason to separate.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Booking service owns reservations
Billing service owns charges
Contract: BookingReserved v1
Failure: billing unavailable does not erase the reservation

Trade-offs

  • Independent scaling and releases require independent data ownership.
  • A shared database can recouple supposedly independent services.
  • A modular monolith is a useful baseline for comparing operational cost.

When to avoid it

Avoid splitting services solely by technical layer or to imitate a larger company.

Your turn

Name three costs that appear when a module becomes a service.

Reveal a worked answer

Network calls can fail independently, releases need contract compatibility, and data cannot be updated with one local transaction. Add observability, bounded retries, and a recovery workflow before splitting.

Keep exploring

Open this lesson
OPTIONAL EXPLORATION10 min read

CQRS

Separate writes from read models when their needs diverge.

Before you beginmicroservices

The problem and the pattern

A reservation command checks capacity and creates a booking. A dashboard query needs a tenant summary optimized for reading. CQRS separates these responsibilities; it does not require separate databases, an event bus, or event sourcing. Start with distinct handlers and measure before adding projection infrastructure.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
public sealed record ReserveBookingCommand(string TenantId, int Seats);
public sealed record TenantBookingSummary(int BookingCount, int Seats);
// Command enforces invariants. Query projects the dashboard view.

Trade-offs

  • Different models can simplify complex reads and writes.
  • Asynchronous projections add lag, replay, and monitoring work.
  • CQRS and event sourcing are independent decisions.

When to avoid it

Avoid separate projection infrastructure for simple CRUD when a direct query already meets the requirement.

Your turn

A newly created booking does not appear in an asynchronous dashboard immediately. What contract must the UI understand?

Reveal a worked answer

The projection is eventually consistent. Return a receipt for the accepted write, explain the dashboard freshness, and monitor projection lag. Do not imply a successful write was lost merely because a read model has not caught up.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Event-driven integration

Communicate facts without hiding ownership.

Before you beginmicroservices

The problem and the pattern

BookingReserved is a fact about a committed reservation. Consumers decide what that fact means inside their own context. A queue decouples availability but creates delivery, ordering, and schema-evolution responsibilities. State who publishes, who consumes, and how failures are retried or quarantined.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
C#
public sealed record BookingReserved(
    Guid EventId, Guid BookingId, string TenantId,
    DateTimeOffset OccurredAt);

Trade-offs

  • Asynchronous integration reduces temporal coupling.
  • Schemas and delivery guarantees become part of the contract.
  • Carry minimal necessary data and avoid secrets in durable events.

When to avoid it

Avoid events for a request that needs an immediate authoritative answer from the owning service.

Your turn

A consumer receives the same event twice and an older event after a newer one. What assumptions should it avoid?

Reveal a worked answer

Do not assume exactly-once or global order. Deduplicate by event identity where needed, use an aggregate version if ordering matters, and define replay behavior. Monitor poison messages rather than retrying forever.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Transactional outbox

Close the gap between a database commit and a message publish.

Before you beginevent-driven

The problem and the pattern

Saving a booking and then publishing to a broker can lose the event if the process crashes between the two operations. Write the booking and an outbox row in one database transaction. A separate dispatcher publishes the row and records delivery. A crash after publish can still cause duplicate delivery.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
BEGIN;
INSERT INTO bookings(id, tenant_id) VALUES ($1, $2);
INSERT INTO outbox(id, kind, payload)
VALUES ($3, 'BookingReserved', $4);
COMMIT;
-- A dispatcher later claims and publishes pending rows.

Trade-offs

  • No distributed transaction is required between DB and broker.
  • The dispatcher needs locking, retry limits, and lag monitoring.
  • Retention and deduplication windows must support the replay policy.

When to avoid it

Avoid an outbox when no external effect must be coupled to a local commit.

Your turn

The dispatcher crashes after broker acknowledgement but before marking the row sent. What must the consumer support?

Reveal a worked answer

The row can be published again. Make the consumer idempotent using event IDs and a durable deduplication record committed with its effect. The outbox prevents lost publish intent, not all duplicate deliveries.

Keep exploring

Open this lesson
OPTIONAL EXPLORATION10 min read

Saga and compensation

Coordinate a business process across local transactions.

Before you begintransactional-outbox

The problem and the pattern

A booking workflow may reserve capacity, request payment, then confirm the reservation. If payment fails, release capacity through an explicit compensating action. A saga records progress and recovery decisions. Compensation is a new business action; it is not a database rollback across services.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Reserve capacity → request payment → confirm booking
Payment fails → release capacity
Payment outcome unknown → reconcile before retrying charge

Trade-offs

  • Long-running workflows become observable and recoverable.
  • Compensation can fail and needs its own retries and escalation.
  • Business stakeholders must define acceptable intermediate states.

When to avoid it

Avoid sagas for work that fits safely into one local database transaction.

Your turn

Payment times out after the provider may have charged the card. Why is immediately charging again dangerous?

Reveal a worked answer

A timeout does not prove failure. Reconcile using the provider operation ID or idempotency key, then decide whether to retry or compensate. Persist workflow state and make each step repeatable.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Idempotency

Make a repeated request have one intended effect.

Before you begintransactional-outbox

The problem and the pattern

A caller retries a booking after losing the response. Accept an idempotency key scoped to the tenant and operation, store a request fingerprint and result, and use a unique constraint to arbitrate concurrent requests. Reusing a key for different input should produce a documented conflict.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
UNIQUE (tenant_id, operation, idempotency_key)

Key exists + matching fingerprint → replay saved result
Key exists + different fingerprint → conflict
New key → commit effect and saved result together

Trade-offs

  • Idempotency reduces duplicate effects but requires durable state.
  • Define key retention and response replay semantics.
  • Do not put sensitive payloads in plain idempotency keys.

When to avoid it

Avoid claiming a GET-like read cache is sufficient protection for a state-changing operation.

Your turn

Two identical requests with one key arrive simultaneously. Why is an in-memory dictionary insufficient across two app instances?

Reveal a worked answer

Each process has its own dictionary and both can create a booking. Enforce uniqueness and commit the operation record with the business write in PostgreSQL. Test concurrency and recovery after process restart.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Cache-aside

Accelerate reads while acknowledging staleness.

Before you beginidempotency

The problem and the pattern

The application first checks a cache and loads the authoritative store on a miss. Include tenant and representation version in the cache key. Expire entries and invalidate them after successful writes. A concurrent read can still repopulate stale data, so decide whether bounded staleness is acceptable.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
Go
key := "tenant:" + tenantID + ":booking:" + bookingID
if value, ok := cache.Get(key); ok {
    return value, nil
}
value, err := store.Find(ctx, tenantID, bookingID)
if err != nil { return Booking{}, err }
cache.Set(key, value, ttl)
return value, nil

Trade-offs

  • Lower latency comes with invalidation complexity.
  • Protect against stampedes with bounded coordination and jittered expiry.
  • A cache outage should have a tested fallback and load budget.

When to avoid it

Avoid caching authorization decisions or capacity invariants without a clear invalidation and consistency model.

Your turn

A cache key uses only the booking ID. What isolation assumption is missing?

Reveal a worked answer

The key does not express tenant scope. Include the authorized tenant and any permission-sensitive representation context. Authorization must still run; a cache hit must not bypass access control.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Retry with a budget

Repeat transient work without multiplying damage.

Before you begincache-aside

The problem and the pattern

A short network interruption may justify retrying a read. Invalid input or a permission denial will not improve with repetition. Bound attempts, add backoff with jitter, honor the operation deadline, and verify that a write is safe to repeat before retrying it.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Attempt 1 → transient failure
Wait: bounded exponential backoff + jitter
Attempt 2 → success
Stop when total deadline or attempt budget is exhausted

Trade-offs

  • Retries improve resilience only for appropriate transient failures.
  • They consume latency and downstream capacity.
  • Use a single policy owner where possible and expose retry metrics.

When to avoid it

Avoid retrying non-idempotent writes when the previous result is unknown.

Your turn

A handler, repository, and HTTP client each retry three times. What can happen to downstream load?

Reveal a worked answer

Nested policies can multiply attempts rather than add them. Put retry ownership at a deliberate boundary, propagate one deadline, and measure total attempts and latency. A retry storm can turn a short outage into overload.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Circuit breaker

Stop spending calls on a dependency that is failing.

Before you beginretry

The problem and the pattern

A breaker opens after a configured failure threshold and rejects calls for a recovery window. A small half-open probe tests whether the dependency has recovered. This protects latency and capacity; it does not repair the dependency or replace timeouts.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Closed: allow calls and observe failures
Open: fail fast for a recovery window
Half-open: allow a bounded probe
Healthy probe → close; failed probe → reopen

Trade-offs

  • Fast failure preserves resources during an outage.
  • Thresholds need workload evidence to avoid oscillation.
  • Provide a useful error and observable state instead of hiding the outage.

When to avoid it

Avoid adding a breaker to local operations with no independent failure boundary.

Your turn

Which failures should trip a payment-service breaker: a timeout or an invalid card request?

Reveal a worked answer

A dependency timeout can indicate unavailability; a client validation error usually should not count as dependency failure. Choose metrics and thresholds for the actual operation, and test recovery rather than only opening.

Keep exploring

Open this lesson
OPTIONAL EXPLORATION10 min read

API gateway

Give clients one entry without centralizing every business rule.

Before you begincircuit-breaker

The problem and the pattern

A gateway can terminate TLS, route traffic, and apply shared request policies. Service-specific authorization and data invariants still belong in the owning service. Keep the gateway observable and redundant because its failure can affect many capabilities.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Client → gateway
/bookings → booking service
/billing → billing service
Gateway: routing, TLS, limits
Services: resource authorization and domain rules

Trade-offs

  • A gateway simplifies client entry points.
  • It can become a bottleneck or a release dependency.
  • Use clear timeouts and avoid gateway-specific domain logic.

When to avoid it

Avoid deploying a gateway when one small service and a reverse proxy already cover the requirements.

Your turn

A gateway validates the token. May the booking service trust a user-supplied tenant header?

Reveal a worked answer

No. Forward identity only through a trusted, validated boundary and still enforce tenant membership and resource permission in booking. Strip or replace spoofable identity headers at the gateway.

Keep exploring

Open this lesson
CONNECTING THE PIECES10 min read

Strangler Fig migration

Replace a legacy capability in reversible slices.

Before you begincircuit-breaker

The problem and the pattern

Place routing in front of the old system and direct a bounded booking capability to the new implementation. Compare behavior and migrate data ownership deliberately. Keep routing reversible until the new path is proven, then retire the replaced legacy slice.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Route by capability
Legacy: existing booking reads
New: reservation creation for a selected tenant cohort
Observe → reconcile → expand → retire old path

Trade-offs

  • Incremental replacement reduces all-or-nothing release risk.
  • Temporary integration and dual-running costs are real.
  • Define cutover and retirement criteria before adding the new slice.

When to avoid it

Avoid a strangler migration without a usable routing seam or an agreed data-ownership transition.

Your turn

Why can independent writes to old and new databases create a migration trap?

Reveal a worked answer

Either write can fail, producing divergent state with no authoritative owner. Choose one write owner, use a reliable replication or outbox path if necessary, and verify reconciliation before shifting readers.

Keep exploring

Open this lesson
Operations

Ship with confidence

Configuration, drift, delivery, and operational readiness.

CONNECTING THE PIECES8 min read

Desired State Configuration

Describe the state you want before applying it.

Before you beginstrangler-fig

The idea

Microsoft DSC uses configuration documents to describe resource instances and their desired properties. Resource implementations provide the meaning of get, test, and set. Inspect installed resources and use a disposable lab before changing state. Keep credentials out of versioned documents.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
dsc resource list
dsc config get --file lab.dsc.yaml
dsc config test --file lab.dsc.yaml
# Review the test result before applying:
dsc config set --file lab.dsc.yaml

Decisions that matter

  • Declarative documents improve repeatability when resource behavior is reliable.
  • Resource availability differs by environment and installed version.
  • Application rollback and configuration rollback need separate plans.

Your turn

What must you check before applying a configuration copied from another machine?

Reveal a worked answer

Verify the schema and DSC version, installed resource types and versions, target environment, permissions, and every intended state change. Run get and test in a disposable lab first. A valid document does not imply the changes are safe for a production host.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

DSC get, test, and set

Observe, compare, then converge.

Before you begindsc-documents

The idea

Get retrieves current resource state. Test compares it with desired state and reports whether it matches. Set enforces the desired state. These are different operations: a successful get does not show compliance, and set can change the machine. Inspect the command output and process exit status according to the installed CLI version.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
dsc config get --file lab.dsc.yaml
dsc config test --file lab.dsc.yaml
dsc config set --file lab.dsc.yaml
dsc config test --file lab.dsc.yaml

Decisions that matter

  • Get is observation; test is comparison; set may mutate resources.
  • Inspect per-resource results in addition to command completion.
  • Run practice configurations only in the intended disposable environment.

Your turn

After set succeeds, why run test again?

Reveal a worked answer

Verify the resulting state rather than assuming execution success equals convergence. Save the before and after evidence, investigate resources that still differ, and confirm any dependent service is actually healthy.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Drift and idempotent configuration

Converge repeatedly without repeated disruption.

Before you begindsc-get-test-set

The idea

Drift is the difference between desired and observed state. An idempotent resource should converge to the same state when applied repeatedly. A script that restarts a service on every run may reach the desired state while still causing unnecessary disruption. Measure both state and side effects.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Baseline: set → test says in desired state
Repeat: set → no unnecessary change
Introduce drift in the disposable lab
Observe: test detects the mismatch
Repair: set → test confirms convergence

Decisions that matter

  • A drift report needs a known desired version to be meaningful.
  • Automatic remediation can repeat a bad configuration; stage and review changes.
  • Detecting drift and choosing to repair it are separate policy decisions.

Your turn

Design evidence that a resource is idempotent rather than merely successful twice.

Reveal a worked answer

Record resource state, reported changes, and relevant side effects across two applications. The second should not repeat destructive or disruptive work. Introduce controlled drift and confirm one repair followed by a stable repeat.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

CI/CD as a chain of evidence

Promote the artifact you tested.

Before you begindrift-idempotency

The idea

Build one immutable artifact, run rule and integration tests, scan it, and promote that same artifact through environments. Record the source revision, dependencies, migration version, and configuration contract. Rebuilding separately for production introduces an untested difference.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Source revision
  → tests + dependency checks
  → reproducible build
  → signed or checksummed artifact
  → staging smoke checks
  → production deployment + verification

Decisions that matter

  • Fast feedback comes from small early checks and meaningful later boundary tests.
  • A green pipeline proves its checks, not every production assumption.
  • Deployment identity should have only the permissions needed to deploy.

Your turn

A staging image passed tests, but production rebuilds from a moving branch. What evidence is missing?

Reveal a worked answer

There is no proof production runs the tested artifact. Promote the same digest, record the deployment revision, and verify external behavior. Keep secrets injected at runtime rather than baked into the artifact.

Keep exploring

Open this lesson
CHECKPOINT8 min read

Operational readiness checkpoint

Make the service supportable before release.

Before you begindelivery-pipeline

The idea

A release checklist should name service ownership, alerts, expected load, backup recovery, and rollback. Run a representative journey through the public domain. Test dependency failure and shutdown behavior in staging. A checklist is useful only when its claims link to observed evidence.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
[ ] Exact artifact revision recorded
[ ] Required dependencies ready
[ ] Public DNS and TLS verified
[ ] Representative read/write smoke checks pass
[ ] Backup restored in a test environment
[ ] Previous release and rollback procedure available

Decisions that matter

  • Run destructive drills in a controlled environment with an owner.
  • Define alert thresholds from actual service objectives.
  • A backup file is not proof of recoverability until a restore works.

Your turn

Choose one failure drill for a booking service and state the expected user and operator experience.

Reveal a worked answer

Temporarily deny database access in staging. Readiness should fail, users should receive a bounded generic error, and operators should see an actionable alert without secret leakage. Restore access and verify recovery without a restart if the pool supports it.

Keep exploring

Open this lesson
Security

Build security in

From trust boundaries to verified remediation.

CONNECTING THE PIECES8 min read

Security architecture

Design controls around assets and trust boundaries.

Before you beginrelease-readiness

The idea

For the booking SaaS, tenant isolation and reservation integrity are assets worth protecting. Map identities, data stores, entry points, and privileged operations. Place enforcement where authority is known and verify the same control through every entry point.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Assets: tenant bookings, identities, payment references
Trust boundaries: browser → API → database
Controls: resource authorization, parameterized SQL, audit events
Evidence: negative tenant-isolation tests

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Name a control that belongs in the application even when a reverse proxy exists.

Reveal a worked answer

Resource authorization must remain at the application boundary because the proxy does not own booking data and tenant membership. Test direct application access in a controlled environment as well as the public route.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Threat modeling

Turn a data-flow diagram into testable abuse cases.

Before you beginsecurity-architecture

The idea

Draw how the browser, identity provider, API, database, and payment service exchange data. Mark trust boundaries and ask how a caller could spoof identity, tamper with input, disclose another tenant’s data, or exhaust a resource. Rank concrete threats by impact and plausible exposure.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Browser → [trust boundary] → Booking API
Booking API → tenant-scoped PostgreSQL
Booking API → payment provider
Threat: valid user requests another tenant's booking
Mitigation: trusted tenant predicate + negative test

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Write one abuse case for a booking export endpoint.

Reveal a worked answer

A legitimate user changes an export identifier to download another tenant’s records. Require resource-level tenant authorization for generation and download, avoid predictable public URLs, and add a regression test for cross-tenant access.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Secure coding

Treat validation, encoding, and authorization as different controls.

Before you beginthreat-modeling

The idea

Validate shape and size at input boundaries. Bind SQL parameters rather than concatenating input. Encode untrusted text for its output context. Authorization still has to decide whether the caller may act on a valid identifier; well-formed input is not permission.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
Go
err := pool.QueryRow(ctx,
    "SELECT id FROM bookings WHERE tenant_id=$1 AND id=$2",
    tenantID, bookingID,
).Scan(&id)
C#
var result = await db.Bookings
    .Where(b => b.TenantId == tenantId && b.Id == bookingId)
    .SingleOrDefaultAsync(ct);

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Why should a lesson renderer escape code text even though it is presented inside a code element?

Reveal a worked answer

HTML is parsed inside code elements. A literal closing tag or script text could become markup without escaping. Escape source text before adding trusted highlighting spans, and test malicious snippets through the renderer.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

OWASP Top 10

Use risk categories to ask better questions.

Before you beginsecure-coding

The idea

The OWASP Top 10 is an awareness document about major web application security risks. Use it to prompt reviews of access control, configuration, injection, dependency integrity, and error handling. It is not an exhaustive test plan or a claim of compliance by itself. Record the edition used in your review.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Review question: can tenant A read tenant B's booking?
Control: authorize every object operation
Test: same booking ID, different authenticated tenant
Evidence: no booking data returned

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Turn one risk category into a concrete booking API verification task.

Reveal a worked answer

For injection, enumerate SQL construction sites, replace concatenation with parameter binding, and test an input containing SQL metacharacters as ordinary data. Verify both result correctness and absence of unintended data access.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

OWASP ASVS

Turn security intent into explicit requirements.

Before you beginowasp-top10

The idea

ASVS provides verifiable application security requirements. Select requirements for the application’s risk and record their version and identifiers. Link each chosen requirement to a control owner, test, and evidence. An unchecked requirement needs a reason and disposition rather than silently disappearing.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Requirement version + identifier
  → application control
  → automated test or review procedure
  → evidence at a source revision
  → owner and review date

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Why is “we follow ASVS” less useful than a requirement-to-evidence matrix?

Reveal a worked answer

The matrix says which requirements apply, how they are enforced, and what evidence proves them at a specific revision. It exposes exclusions and gaps instead of allowing a general claim to imply complete coverage.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

SAST

Inspect source and build artifacts before deployment.

Before you beginasvs

The idea

Static application security testing analyzes code or artifacts without exercising a live application. It can detect suspicious data flows and insecure API usage, but it needs context and triage. Add rules and dependency checks to CI, assign an owner, and validate findings with a minimal reproduction.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Source revision → SAST scan → finding triage
Finding: user input reaches SQL concatenation
Fix: parameter binding
Verification: regression test + clean rescan

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

A scanner reports a false positive in a tenant-safe query. How should the suppression be recorded?

Reveal a worked answer

Document the code location, rule, analysis of the data flow, evidence, owner, and review condition. Scope the suppression narrowly and reconsider it after changes; do not disable the entire rule to quiet one result.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

DAST

Exercise a running application from its exposed interface.

Before you beginsast

The idea

Dynamic application security testing observes a running target. Use a controlled staging environment with written scope and test accounts for different roles and tenants. DAST can expose runtime configuration and behavior that static analysis misses, while coverage depends on reachable paths and authentication.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Authorized staging target
  → authenticate as test tenant A
  → exercise documented API paths
  → inspect findings
  → verify against negative authorization tests

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Why can an unauthenticated DAST scan miss a cross-tenant booking export flaw?

Reveal a worked answer

It cannot reach the authenticated flow or compare two tenant contexts. Configure scoped accounts and seeded data, then verify authorization with explicit negative cases. A clean scan is limited by the paths and identities exercised.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Authentication and authorization

Check identity, action, and resource separately.

Before you begindast

The idea

Authentication establishes who is calling. Authorization checks whether that identity may perform the requested action on this resource. A SaaS API should bind requests to trusted tenant membership and apply object-level checks. Deny by default when permission cannot be established.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Identity valid? → action permitted? → tenant owns resource?
Only then execute the booking operation.
Test anonymous, wrong role, wrong tenant, and valid caller.

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

A user can list their own bookings but download any attachment by ID. What failed?

Reveal a worked answer

The attachment endpoint missed object-level authorization. Apply the same trusted tenant and ownership checks to downloads, exports, and indirect IDs. Add a regression test and review sibling endpoints for the same pattern.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Safe cryptography

Use established constructions and manage the keys.

The idea

Use maintained platform libraries and approved protocols rather than designing ciphers. Passwords need a dedicated password-hashing scheme with a per-password salt and an appropriate cost. Encryption needs key management, rotation, authenticated integrity, and clear ownership. TLS protects a transport path, not all stored data.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Need confidentiality + integrity? → authenticated encryption
Need password verification? → dedicated password hash
Need random token? → cryptographically secure generator
Keep keys outside source and logs.

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Why is hashing a password once with a fast general-purpose hash inadequate?

Reveal a worked answer

Fast hashes permit attackers to test guesses cheaply. Use the platform identity stack or a maintained password-hashing implementation with tunable cost and salts. Store algorithm and cost metadata so hashes can be upgraded.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Penetration testing scope and reporting

Make authorization and evidence clear before testing.

Before you beginsafe-cryptography

The idea

A penetration test begins with written authorization, named targets, allowed techniques, time windows, test accounts, data handling rules, and a contact for stopping the test. Reports should connect a reproducible issue to business impact and remediation. Keep exercises inside owned test fixtures and disposable environments.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Scope: staging booking API only
Accounts: tenant-a-reviewer, tenant-b-reviewer
Excluded: payment provider and production identities
Report: steps, affected version, impact, fix, retest result

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

A staging API redirects to a third-party payment page. Is that page automatically in scope?

Reveal a worked answer

No. The third party is a separate target and requires explicit authorization. Stop at the agreed boundary and document the integration assumption. Use provider sandbox fixtures for the defensive exercise.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Vulnerability management

Move a finding to an owned, verified outcome.

Before you beginpentest-scope

The idea

A useful finding includes an affected asset and version, reproduction evidence, plausible impact, and an owner. Prioritize using exposure, exploitability, business criticality, and existing controls, alongside severity scores. Track accepted risk separately from a verified fix and include a review date.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Detect → validate → prioritize → assign
  → remediate → regression test → rescan/retest
  → verified closure with revision and evidence

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

A critical library advisory affects a package that the running service does not load. Can it be ignored immediately?

Reveal a worked answer

Validate the dependency path and deployed artifact, document exposure and reachability, and still plan an update or an explicit risk disposition. Do not equate a scanner label with complete application context.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

Remediation verification

Prove the exploit path stopped working without breaking the feature.

Before you beginvulnerability-management

The idea

A code change is not closure evidence. Reproduce the original flaw against the old fixture, apply the fix, then show the same case fails safely and the authorized use still succeeds. Re-run the relevant scanner or manual procedure and record the tested source and artifact revisions.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Before: tenant B can read tenant A's fixture booking
After: cross-tenant request returns no data
Positive control: tenant A still reads its own booking
Evidence: test IDs + build revision + retest date

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

What should the retest include if the original flaw was in CSV exports?

Reveal a worked answer

Exercise the export creation, status, and download routes, including expired links and another tenant’s identifiers. Check the actual exported bytes for forbidden data. A JSON endpoint test alone cannot verify the CSV fix.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

CVE and CWE

Distinguish a specific vulnerability from a weakness class.

Before you beginremediation-verification

The idea

A CVE identifier names a publicly disclosed vulnerability record. A CWE identifier classifies a kind of software weakness. Use CVE for affected product and version tracking, and CWE to group root causes and improve coding practices. Neither identifier alone proves the service is exploitable.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Specific vulnerability: CVE record + affected versions
Weakness category: CWE classification
Local assessment: deployed version + configuration + exposure
Outcome: update, mitigation, or owned risk decision

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

How would you use these identifiers after fixing SQL injection in your own test fixture?

Reveal a worked answer

Classify the root weakness with the appropriate CWE when supported by the analysis. Record affected internal revisions and the regression test. Do not invent a CVE: CVE assignment follows the program’s process.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

CPE and product inventory

Know what software is actually deployed.

Before you begincve-cwe

The idea

Common Platform Enumeration describes product naming for inventory and vulnerability matching. Combine product and version identifiers with package lock files, artifact digests, and an inventory of deployed services. A product-name match is a lead that needs version and configuration validation.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Asset: booking-api production
Artifact: immutable digest
Packages: module + locked version
Product identifier: CPE when applicable
Match advisory → verify deployed applicability

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

A vulnerability feed matches a similarly named product. What do you verify before opening an urgent remediation task?

Reveal a worked answer

Confirm vendor, product, edition, affected version range, platform, and whether the vulnerable component is present in the deployed artifact. Preserve the evidence and avoid treating an ambiguous name match as confirmed exposure.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

PCI DSS in the application design

Understand how payment data changes system scope.

Before you begincpe-inventory

The idea

PCI DSS concerns environments that store, process, or transmit payment account data and systems that can affect their security. For the booking capstone, use a payment provider’s test flow and retain a provider reference instead of card data. Determine actual scope and validation obligations with the responsible payment and assessment parties.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Browser → payment provider test flow
Booking API stores: provider reference + booking status
Booking API excludes: raw card number, security code
Verify logs, traces, and error reports also exclude card data.

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Why does using a hosted payment page not justify claiming the whole business is PCI compliant?

Reveal a worked answer

The integration reduces some data handling but scope depends on the actual architecture, controls, and applicable validation. Map flows and responsibilities, verify the provider integration, and have the responsible parties determine requirements. A course exercise is not an assessment.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

ISO/IEC 27001

Connect application controls to an information security management system.

Before you beginpci-dss

The idea

ISO/IEC 27001 specifies requirements for an information security management system. It connects organizational context, risk assessment, treatment, operation, evaluation, and improvement. Application tests can provide evidence for a control, but a secure endpoint alone does not establish organizational certification.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Information asset → risk assessment → treatment owner
Control evidence → monitoring and review
Incident lesson → corrective action → improvement

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

How can the booking team make its tenant-isolation tests useful to an organizational security program?

Reveal a worked answer

Record the protected asset, risk, control owner, test procedure, source revision, result, and review schedule. Link failures to corrective work. Keep the application evidence distinct from the organization-wide management-system requirements.

Keep exploring

Open this lesson
CONNECTING THE PIECES8 min read

NIST SSDF

Build security work into the development lifecycle.

Before you beginiso27001

The idea

NIST SSDF organizes secure development practices around preparing the organization, protecting software, producing well-secured software, and responding to vulnerabilities. Map practices to owners and repeatable evidence. Integrate threat review, dependency controls, protected builds, and remediation into ordinary delivery.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Prepare: roles + requirements
Protect: source and artifact integrity
Produce: review + tests + secure build
Respond: intake + triage + verified remediation

Decisions that matter

  • Choose a control against a concrete risk and document its owner.
  • Exercise negative cases in authorized test fixtures.
  • Retain evidence at a specific revision and revisit it when the system changes.

Your turn

Choose one SSDF-aligned practice and name the evidence your capstone can produce.

Reveal a worked answer

For vulnerability response, keep a sample finding with an owner, impact assessment, affected revision, fix, regression test, and verified retest result. For artifact protection, record the exact tested artifact digest and deployment provenance.

Keep exploring

Open this lesson
Capstone

Connect the pieces

A small SaaS API. A complete engineering story.

CHECKPOINT20 min read

Build the booking SaaS API

Bring language, architecture, and operations together.

Before you beginnist-ssdf

The idea

Build a tenant-scoped API that creates and reads bookings against PostgreSQL. Choose a modular monolith with an explicit booking application boundary unless a measured need justifies more complexity. Provide C# and Go implementations of the same reserve-and-read use case and document how dependency wiring differs.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
POST /bookings: validate input, authorize tenant, reserve atomically
GET /bookings/{id}: return only within authorized tenant
GET /healthz: bounded readiness check
Evidence: migrations, test results, architecture decisions

Decisions that matter

  • Keep the scope small enough that all boundary tests can run.
  • Use the same API and data contract for the C# and Go comparison.
  • Record simplifications and remaining risks instead of implying production certification.

Your turn

Submit a release candidate with an architecture decision record, threat model, test report, and operational checklist. Explain one pattern you deliberately avoided.

Reveal a worked answer

A strong submission states the consistency invariant, tenant trust boundary, error contract, migration identity, and recovery path. It demonstrates concurrent final-seat reservations and cross-tenant denial. Avoiding microservices because one team and one deployment meet the need is a defensible decision when supported by the constraints.

Keep exploring

Open this lesson
CHECKPOINT15 min read

From finding to verified remediation

Demonstrate the full security feedback loop.

Before you beginsaas-capstone

The idea

Create a test fixture with a booking owned by tenant A and a caller from tenant B. Capture a failing authorization regression against the deliberately vulnerable fixture. Add the tenant predicate and resource check, rerun the reproduction, and preserve the positive authorized case. Connect this evidence to a release revision.

Follow the flow

Make it concrete

This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.

Focused example
text
Finding: cross-tenant booking access in owned fixture
Before: negative test fails by returning foreign data
Fix: trusted tenant + booking ID query
After: negative and positive controls pass
Close: link source revision, test evidence, and retest result

Decisions that matter

  • Keep intentionally vulnerable fixtures isolated from the deployed service.
  • Verification must test the original path, not only nearby code.
  • A successful retest closes the specified finding, not every security risk.

Your turn

Write a concise remediation report that another reviewer can reproduce without access to production data.

Reveal a worked answer

Include the fixture setup, exact method and route, test identities, observed before and after outcomes, affected and fixed revisions, root cause, regression test IDs, and retest result. Use synthetic records and omit tokens and private data.

Keep exploring

Open this lesson