> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Azure Architecture

What gets deployed when you run `infra:deploy` on Azure and how traffic flows through the system.

## High-Level Architecture

```
                                Internet
                                    |
                                    v
                    +-------------------------------+
                    |   Azure Front Door            |
                    |   - WAF (custom + managed)    |
                    |   - CDN (global edge caching) |
                    |   - Managed SSL certificates  |
                    |   - Load balancing             |
                    +------+--------+--------+------+
                           |        |        |
                           v        v        v
                    api.x.com  app.x.com  spa.x.com
                           |        |        |
                           v        v        v
                   +--------+  +--------+  +----------+
                   | Kong   |  | Next.js|  | Blob     |
                   | App Svc|  | App Svc|  | Storage  |
                   +----+---+  +--------+  +----------+
                        |
                [VNet integration]
                [Private DNS zone]
                        |
          +-------------+-------------+
          |             |             |
          v             v             v
   +-----------+  +-----------+  +-----------+
   |auth-svc   |  |bff-svc    |  |offers-svc |
   |Container  |  |Container  |  |Container  |
   |App (ILB)  |  |App (ILB)  |  |App (ILB)  |
   +-----+-----+  +-----+-----+  +-----+-----+
         |               |               |
         v               v               v
+----------------+ +---------------+ +---------------+
| PostgreSQL     | | Managed Redis | | Key Vault     |
| Flexible Server| | (Balanced B0) | | (RBAC mode)   |
+----------------+ +---------------+ +---------------+
```

## Standard vs Premium Tier

The architecture has two security tiers controlled by the `frontdoorPremium` toggle in `infrastructure.json`.

### Standard — secure by default

Standard is the default and provides strong security within Azure's constraints. Front Door terminates TLS at the edge, applies WAF rules, and forwards traffic to your origins. Since Azure Standard Front Door doesn't include Microsoft's managed WAF rulesets, tsdevstack generates \~75 custom WAF rules that cover the same ground: SQLi, XSS, path traversal, command injection, SSRF, scanner fingerprints, known CVEs, rate limiting, and protocol abuse.

Origin protection uses App Service Access Restrictions — a **platform-level** networking feature. The generated Terraform sets `ip_restriction_default_action = "Deny"` on each App Service, with a single Allow rule for the `AzureFrontDoor.Backend` service tag filtered by the Front Door instance's FDID (`x_azure_fdid` header). Traffic that doesn't match is rejected by Azure's platform before it ever reaches your container. The origins do have public endpoints, but the platform denies any request that didn't come through your specific Front Door instance.

Each app's Kudu site (App Service's deployment and log stream site, `{app}.scm.azurewebsites.net`) has its own access rule: it accepts only an Azure sign-in with deploy rights on the app. Username/password sign-in and SSH into the containers are off. `infra:logs --follow` reads Kong's and the Next.js apps' live logs there, with the environment's credentials.

### Premium — Private Link + managed rulesets (+$295/month)

Premium adds two things. First, **Private Link origins** — Front Door connects to App Service over Azure's backbone network instead of the public internet. Your App Service origins have zero public surface. Second, **Microsoft managed WAF rulesets** (DRS 2.1 Default Rule Set + Bot Manager 1.1) — professionally maintained rules updated by Microsoft's security team. With managed rulesets handling SQLi, XSS, and common attack patterns, the custom rule count drops from \~75 to \~31 (covering rate limiting, restricted paths, scanner fingerprints, CVE patterns, and protocol abuse that managed rulesets don't address).

### Comparison

| Aspect               | Standard                                                 | Premium                                           |
| -------------------- | -------------------------------------------------------- | ------------------------------------------------- |
| SKU                  | `Standard_AzureFrontDoor`                                | `Premium_AzureFrontDoor`                          |
| Origin connection    | Public endpoints + Access Restrictions (FDID validation) | Private Link to App Service (zero public surface) |
| WAF managed rulesets | None (not available on Standard)                         | DRS 2.1 + Bot Manager 1.1                         |
| WAF custom rules     | \~75 (full coverage written by tsdevstack)               | \~31 (managed rulesets cover the rest)            |
| Monthly cost delta   | Base (\~$35)                                             | +$295/month (\~$330 total)                        |

Standard is production-ready — the 75 custom WAF rules provide equivalent coverage to the managed rulesets. Premium is worth it when you need Private Link for compliance requirements (e.g. zero public surface) or prefer Microsoft-maintained WAF rules over custom ones.

WAF rules can be customized via `infrastructure.json` — including custom match rules and rate limit rules using Azure's native match conditions. See [Service Configuration — WAF Rules](/docs/infrastructure/service-configuration.md#waf-rules) for details.

## Compute: App Service + Container Apps

**App Service (Kong + Next.js):**

- Kong and Next.js run on App Service (not Container Apps) for:
  - Front Door Access Restrictions with FDID header validation
  - Always-available gateway (`always_on: true`)
- Default SKU: B1 (\~$13/month per instance), a fixed instance count (`minInstances`, at least 1)
- Standard (S1, \~$69/month per instance) and Premium plans autoscale on CPU between `minInstances` and `maxInstances`, with App Service health checks when more than one instance runs. See [Azure App Service plans](/docs/infrastructure/service-configuration.md#azure-app-service-plans)
- VNet integrated for outbound traffic to Container Apps
- Next.js apps must answer `/health` with 200 (the framework template includes the route). Front Door probes it to decide whether the app is up, and App Service's health check uses it too
- With Next.js apps, Kong also has a private endpoint. The Next.js servers call Kong at its default host name (`KONG_INTERNAL_URL`), which resolves to that endpoint inside the VNet. Front Door still reaches Kong through its public access, restricted as above

**Container Apps (NestJS backends):**

- Consumption plan with ILB (Internal Load Balancer) — no public IP
- KEDA HTTP scaling enables scale-from-zero with automatic wake-up (2-5s cold start)
- Services are VNet-accessible only via ILB static IP + private DNS zone

## Data: PostgreSQL + Managed Redis

**PostgreSQL Flexible Server:**

- VNet-integrated (postgres subnet, no public access)
- Databases created by Terraform. On every deploy, the `db-init` job (a Container Apps Job) sets up each service's two database users. See [Database users](/docs/local-development/database-migrations.md#database-users)
- Default: `B_Standard_B1ms` (\~$14/month, burstable)
- Migrations run via Container Apps Jobs (in VNet, can reach PostgreSQL)
- Delete lock on the server while `database.deletionProtection` is on (the default). The CLI manages it, not Terraform: `infra:remove-service` and `infra:destroy` lift it while they delete. See [Database](/docs/infrastructure/service-configuration.md#database)

**Azure Managed Redis:**

- `Balanced_B0` (\~$26/month: two nodes, high availability) with `EnterpriseCluster` policy
- Private endpoint only (no public access)
- TLS required, dynamic port (from Terraform output)

:::info
**BullMQ compatibility:** Azure Managed Redis uses `EnterpriseCluster` clustering policy. BullMQ requires a `{bull}` prefix to force all keys to the same hash slot, avoiding `CROSSSLOT` errors. This is Azure-specific — GCP and AWS don't use clustering at the basic tier.
:::

## Storage: Azure Blob Storage

When storage buckets are configured in `config.json`, Terraform creates a shared storage account with blob containers:

- One storage account per project-env: `{project}{env}st{suffix}` (alphanumeric only, max 24 chars; see [Names](#names))
- One blob container per logical bucket name
- Soft delete enabled (7-day retention)
- CORS set to `*` (presigned URLs are the security boundary)

**IAM:** The Container Apps managed identity gets the `Storage Blob Data Contributor` role on the storage account.

**Special:** `AZURE_STORAGE_ACCOUNT_NAME` is injected as an environment variable on Container Apps (not a secret — it's a Terraform output). The Azure Blob adapter uses this alongside managed identity for authentication.

No client secrets in containers — Container Apps use managed identity automatically.

**Access logs:** every read, write and delete of the buckets' files goes to the environment's Log Analytics workspace (`StorageBlobLogs`). See [cost estimation](/docs/infrastructure/providers/azure/cost-estimation.md#storage-access-logs).

For setup and usage, see [Object Storage](/docs/features/object-storage.md).

## Edge: Front Door

Azure Front Door replaces three AWS services (CloudFront + ALB + ACM) with one unified service.

**Features:**

- CDN with global edge caching
- WAF (custom rules or managed rulesets depending on tier)
- Managed SSL certificates (auto-provisioned)
- Load balancing across origin groups

**Standard tier WAF (\~75 custom rules):**

| Priority Range | Category                                                       |
| -------------- | -------------------------------------------------------------- |
| 100-149        | Rate limiting (global, configurable via `infrastructure.json`) |
| 150-199        | Request size limits                                            |
| 200-299        | Restricted paths + methods                                     |
| 300-399        | Scanner fingerprints                                           |
| 400-499        | Known CVE patterns                                             |
| 500-899        | SQLi, XSS, path traversal, Node.js, command injection          |
| 900-999        | Protocol abuse + session fixation                              |
| 1000+          | User custom rules (via `infrastructure.json`)                  |

**Premium tier:** Bands 500-899 are replaced by Microsoft's managed rulesets (DRS 2.1 + Bot Manager), with \~31 custom rules covering rate limiting, restricted paths, scanner fingerprints, CVE patterns, and protocol abuse.

**Access Logging:**

- Diagnostic settings on Front Door profile capture three log categories:
  - `FrontDoorAccessLog` — all incoming requests
  - `FrontDoorHealthProbeLog` — health probe traffic
  - `FrontDoorWebApplicationFirewallLog` — WAF allow/block decisions
- Logs are sent to a Log Analytics workspace

**SPA hosting:**

- Each SPA's files sit in its own storage account (static website), with Front Door in front.
- A path that isn't a file serves `index.html` (client-side routing).

## Networking

```
VNet: 10.0.0.0/16
|
+-- Subnet: container-apps (10.0.0.0/23)
|   +-- Container Apps Environment (ILB, private IP only)
|
+-- Subnet: postgres (10.0.2.0/28)
|   +-- PostgreSQL Flexible Server
|   +-- Service endpoint: Microsoft.Storage (WAL uploads)
|
+-- Subnet: private-endpoints (10.0.3.0/28)
|   +-- Azure Managed Redis Private Endpoint
|   +-- Kong Private Endpoint (with Next.js apps; their servers' calls to Kong)
|
+-- Subnet: app-service-integration (10.0.4.0/25)
|   +-- App Service VNet integration (Kong + Next.js outbound)
|
+-- Private DNS Zones
    +-- private.postgres.database.azure.com
    +-- privatelink.redis.azure.net
    +-- privatelink.azurewebsites.net (Kong's private endpoint; other names fall back to public DNS)
    +-- {cae-default-domain} (Container Apps wildcard A record)
```

Kong (App Service) resolves Container App FQDNs via a private DNS zone with a wildcard A record pointing to the CAE internal static IP.

## Secrets: Key Vault

**RBAC mode** (not legacy Access Policies). Two principals with different roles:

| Principal                                        | Role                                                                                              | Purpose                                                                                                                           |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Service Principal (from `cloud:init`)            | Key Vault Secrets Officer                                                                         | CLI: read + write + delete                                                                                                        |
| Per-service secrets MI (from Terraform)          | Key Vault Secrets User on the shared vault and its own vault                                      | Runtime: read-only secrets (each backend service; workers use their base service's)                                               |
| Container Apps User-Assigned MI (from Terraform) | AcrPull + Key Vault Secrets User on the shared vault                                              | Runtime: image pulls (NestJS backends, workers, jobs)                                                                             |
| Database jobs MI (from Terraform)                | AcrPull + Key Vault Secrets Officer on the database jobs' vault and each database service's vault | The `db-init` job: sets up each service's two database users and writes their URLs. Migration jobs use it to read the owner's URL |

Next.js on App Service gets `AcrPull`, plus the role that lets it send traces. It reads nothing from Key Vault. Kong gets `AcrPull` and read access to exactly three secrets in the shared vault: the Redis password, the trust token and the frontend token. App Service hands them to Kong as environment variables when it starts. They are never in the Kong image.

**One vault per service.** The shared secrets live in `{projectName}-{env}-kv-{suffix}`. Each backend service's own secrets live in `{projectName}-{env}-{service}-{suffix}`, shortened with a hash when longer than 24 characters ([Names](#names)). The CLI creates the service vaults. A service can read the shared vault and its own vault, never another service's.

**The database jobs' vault.** `{projectName}-{env}-dbjobs-{suffix}` holds what only the database jobs may read: the server admin's password and each service's `MIGRATION_DATABASE_URL` (its database owner). A service reads everything in its own vault, so these can't live there. No service can read this vault. The CLI creates it, and `dbjobs` can't be a service name. See [Database users](/docs/local-development/database-migrations.md#database-users).

**Zero-credential runtime:** Container Apps get `SECRETS_PROVIDER=azure`, `AZURE_CLIENT_ID` (the shared identity), `AZURE_SECRETS_CLIENT_ID` (the service's own identity), `AZURE_KEYVAULT_NAME` and `AZURE_SERVICE_KEYVAULT_NAME`. No service principal credentials are injected.

Secret naming auto-transforms underscores to hyphens: `DATABASE_URL` > `DATABASE-URL`.

## Scale-to-Zero

Services run one replica by default (`minInstances: 1`). With `minInstances: 0`, Container Apps use KEDA HTTP scaling: services scale to zero when idle and wake automatically on the next request (2-5s cold start). No wake-up mechanisms needed. Messages for a scaled-to-zero service wait in Redis until a request starts it. See [minInstances](/docs/infrastructure/service-configuration.md#mininstances).

Kong runs on App Service with `always_on: true` — always available with no cold start.

## Security

- **Standard:** Front Door validates requests via Access Restrictions with FDID header matching
- **Premium:** Front Door connects via Private Link (zero public surface on App Service origins)
- App Service's Kudu sites: Azure sign-in with deploy rights only; no username/password sign-in, no SSH
- Kong reads each client's address from `X-Azure-SocketIP`, set by Front Door. The Next.js frontend forwards its visitors' addresses the same way ([Client addresses](/docs/customization/kong-customization.md#client-addresses))
- Backend services are in ILB Container Apps Environment (no public IP)
- NSG rules: Allow LoadBalancer + VNet traffic, deny all others
- Managed Identity for zero-credential runtime (no secrets in containers)

## Logs, Traces and Dashboards

- **Logs:** everything lands in the environment's Log Analytics workspace (`{project}-{env}-logs`). Container Apps write to resource-specific tables (`ContainerAppConsoleLogs`, `ContainerAppSystemLogs`) through a diagnostic setting. Kong and the Next.js apps send their console, platform and HTTP logs, and Front Door its access and WAF logs. `infra:logs` reads them. See [Cloud Logs](/docs/features/cloud-logs.md).
- **Traces:** Application Insights sits on the same workspace, with local authentication off. Services, workers and Next.js apps send their spans to a data collection endpoint and rule, signed in with Entra tokens from their managed identities (**Monitoring Metrics Publisher** on the rule). Spans land in the `OTelSpans` table.
- **Kong's collector:** Kong's App Service runs two containers (site containers): Kong itself on port 8080, and an OpenTelemetry Collector that receives Kong's spans on `localhost` and signs in with Kong's identity. It shares Kong's plan, at no extra charge.
- **Dashboard:** one Azure Monitor workbook per environment in the resource group, created by Terraform. `infra:deploy` prints its link.
- **Database:** the enhanced Postgres metrics are on. Query Store (per-query statistics) is on for General Purpose and Memory Optimized tiers; Microsoft advises against it on Burstable tiers.

See [Traces and Dashboards](/docs/features/traces-and-dashboards.md).

## Cost Estimation

See [Azure Cost Estimation](/docs/infrastructure/providers/azure/cost-estimation.md) for a detailed breakdown across development (scale-to-zero), production (always-on), and scaled scenarios, including Standard vs Premium tier comparisons and links to official Azure pricing pages.

## Async Messaging

Async messaging uses Redis Streams on the same Azure Cache for Redis instance used for caching and BullMQ. No additional Azure resources are created — messaging is a framework-level feature that runs on existing infrastructure. See [Async Messaging](/docs/features/async-messaging.md) for details.

## Names

Some Azure names are unique across all of Azure, not only in your subscription. Each of these carries a 6-character suffix from the subscription ID, so another project with the same name can't take it first:

| Resource                        | Name                                                                      |
| ------------------------------- | ------------------------------------------------------------------------- |
| Key Vaults                      | `{project}-{env}-kv-{suffix}`, `{project}-{env}-{service}-{suffix}`       |
| Terraform state storage account | `{project}{env}tf{suffix}`                                                |
| Storage account (buckets)       | `{project}{env}st{suffix}`                                                |
| Container registry              | `{project}{env}acr{suffix}`                                               |
| Kong and Next.js App Services   | `{project}-{env}-kong-{suffix}`, `{project}-{env}-{app}-{suffix}`         |
| Redis                           | `{project}-{env}-redis-{suffix}`                                          |
| PostgreSQL server               | `{project}-{env}-postgres-{suffix}`, unless `database.serverName` sets it |

A name longer than Azure allows (24 characters for Key Vaults and storage accounts) keeps its start and ends in a hash of the full name. SPA storage accounts already end in part of the subscription ID and don't change.

Environments set up with v0.12.0 or earlier keep the names they have, without the suffix. Every command checks once whether the shared Key Vault exists under its old name, `{project}-{env}-kv`, in `{project}-{env}-rg`. If it does, nothing is renamed. If the check itself fails (permissions, network), the command stops instead of guessing.

## Terraform Resources

The number of Terraform resources grows with your services and settings. They include VNet, subnets, Container Apps Environment, App Service plans, Front Door profile with WAF policy, PostgreSQL Flexible Server, Managed Redis, Key Vault, ACR, DNS zones, and Managed Identity role assignments.
