# Multitenant applications on BTP: when one app should serve many customers

> Decide when an app on SAP BTP should be multitenant, and know how subscription, tenant isolation, routing and upgrades work when it is.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/multitenant-apps-on-btp/
- Updated: 2026-11-27
- Reading time: Foundational 8 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

A **multitenant** app is deployed once and used by many customers, each called a **tenant**. Every tenant gets its own address and its own data, and no tenant can see another's. The provider runs one copy of the code, upgrades it once for everybody, and pays for the platform underneath.

On SAP BTP, each customer gets a **subaccount** in the provider's global account and **subscribes** to the app. Subscribing starts an onboarding step in the app: it creates that tenant's database, sets up its address and returns a link.

Multitenancy is the right design when you sell or provide the same app to many independent organizations. It is the wrong design for most internal apps. Ten departments of one company are users with different authorizations, not ten tenants.

This topic helps you tell the two apart, and explains what a multitenant app costs to build and run when you do need one.

### Why it matters to the business

- **Who it serves.** Multitenancy turns an app into a product. One code line can serve dozens of customers at the cost of one deployment, which is how software vendors and partners on BTP make a business case.
- **Who pays.** SAP's documentation says the resources the app and its consumers use are billed to the provider ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/developing-multitenant-applications-in-the-cloud-foundry-environment-5e8a2b7.md)). If a customer's usage grows, your bill grows, so the price you charge must cover it.
- **The risk.** One bug in tenant handling can show one customer's data to another. That is a data breach, not a defect, and it hits every tenant at once.
- **The trap.** Multitenancy adds onboarding code, per-tenant upgrades, a subscription process and support for many customers. For an internal app with one data owner, all of that is cost with no return.

**Example: Calder Pumpworks (fictional).** Calder's aftermarket team wants a *Fleet portal* where each water utility that buys Calder pumps sees its own pumps, warranty dates and service visits. Brennock Water Utility must never see Ostervale Municipal Water's pumps, and Calder wants one portal to run, not twenty-five. That is a multitenant app. Calder's distributor order-status app is not: its data is Calder's own orders, and each distributor simply sees its own through authorizations.

### How SAP does it

As of November 2026, SAP's documentation describes these building blocks:

- **SAP SaaS Provisioning service** (technical name `saas-registry`). It registers the app so subaccounts can subscribe to it, and it calls the app when a tenant subscribes or unsubscribes ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/register-the-multitenant-application-to-the-sap-saas-provisioning-service-3971151.md)).
- **SAP Authorization and Trust Management service** and the **application router**. Together they read the tenant from the address, log the user in with that tenant's identity provider and hand the app a token that names the tenant ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/configure-the-approuter-application-5af9067.md)).
- **SAP Cloud Application Programming Model (CAP)** with its MTX services. CAP adds subscription handling, a database per tenant and tenant upgrades with one command ([CAP documentation](https://cap.cloud.sap/docs/guides/multitenancy/)).
- **The ABAP environment.** ABAP-based SaaS uses clients in one ABAP system as tenants, orchestrated by the ABAP Solution service ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/multitenant-applications-195031f.md)).
- **The subscription management dashboard.** A screen for the provider to see every subscription, its status and its errors ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/using-the-sap-btp-subscription-management-dashboard-434be69.md)).

SAP's Cloud Foundry guide states that consumers subscribe from subaccounts in the provider's own global account, and that the provider creates and manages those subaccounts ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/providing-multitenant-applications-to-consumers-in-the-cloud-foundry-environment-7a013f1.md)). Selling to companies that run their own global accounts goes through SAP's partner and SAP Store channels; check those terms with SAP before you plan a commercial product.

### Do you need multitenancy? A decision guide

| Situation | Usually the right design | Why |
| --- | --- | --- |
| Many independent customers, one app, you run it | **Multitenant** | One code line, one upgrade, data kept apart per customer |
| One company, many departments, plants or distributors as users | **Single tenant** with authorizations | One data owner; filter by company code, plant or customer |
| Group companies whose data must stay in different regions | **One deployment per region** | Subscribers must be in the provider's region |
| Two or three customers, each wanting its own release or custom code | **One single-tenant deployment per customer** | The tenant machinery costs more than it saves |
| You buy an app that a vendor runs for many customers | **Subscribe as a consumer** | Ask the vendor how it isolates tenants |

Calder's verdicts from the deep layer: the Fleet portal is multitenant; the distributor order-status app and the test certificate archive are single tenant; the shift-handover app for Rockford and Augsburg is two deployments, because Augsburg's data stays in the EU.

### Questions to ask

1. **Who owns the data?** If the answer is "us", you probably need authorizations, not tenants.
2. **How many tenants in two years, and who creates their subaccounts?** The provider does, in its own global account.
3. **How is tenant data kept apart?** A database per tenant, or a shared table with a tenant column? Who has tested that one tenant can't read another?
4. **How does an upgrade reach every tenant, and what happens when one tenant's upgrade fails?**
5. **What happens to a tenant's data when it leaves?** Unsubscribing can delete it. Is there an export, and how long do you keep it?
6. **What does each tenant cost us, and does the price cover it?**
7. **Which regions do customers need?** One deployment serves one region.

### Common misconceptions

- **"Multitenant is more modern, so every BTP app should be."** For an app with one data owner it adds cost, risk and process for nothing.
- **"Each plant or company code is a tenant."** Inside one company these are data dimensions with authorizations. Tenants are for separate data owners.
- **"The platform guarantees isolation."** The platform tells the app which tenant is calling. The app must still keep the data apart, and SAP's ABAP guideline says isolation isn't fully ensured by the infrastructure alone ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/multitenancy-development-guideline-9d994c8.md)).
- **"Upgrading the app upgrades every tenant."** New code goes live once, but each tenant's database must also be upgraded, and one can fail while others succeed.
- **"Customers pay for their own BTP usage."** The provider's account pays; recover it in your price.

### Key terms

- **Tenant:** one customer's separate share of a multitenant app, with its own data and address.
- **Provider:** the organization that builds, deploys and runs the multitenant app.
- **Consumer subaccount:** the BTP subaccount that represents one tenant and subscribes to the app.
- **Subscription:** the link between a consumer subaccount and the app; creating it onboards the tenant.
- **SaaS Provisioning service (`saas-registry`):** the BTP service that registers the app and calls it on subscribe and unsubscribe.
- **Tenant isolation:** the guarantee that one tenant can never read or change another tenant's data.
- **Database per tenant:** an isolation model where each tenant's data lives in its own database or container.
- **Tenant upgrade:** bringing one tenant's database up to the schema the new code expects.

### Check yourself

1. Calder's distributors log in to an app to see the status of their own orders. Should it be multitenant?
   - A. Yes, because each distributor is a separate company
   - B. No, because the orders are Calder's data, filtered per customer
   - C. Yes, because only multitenant apps can serve external users
   - D. No, because BTP doesn't allow external users at all

   Answer: B. The distributors are users of Calder's own data. Authorizations that filter by customer keep each one to its orders, without the cost of tenants, subscriptions and per-tenant upgrades.

2. What is the strongest business reason to build an app as multitenant?
   - A. It makes an internal app look more modern to auditors
   - B. It moves the platform bill from the provider to the users
   - C. It serves many independent customers from one code line
   - D. It removes the need for authorizations inside the app

   Answer: C. Multitenancy pays off when many separate organizations use the same app and the provider runs it once and upgrades it once. It doesn't move costs to consumers, and it doesn't replace authorizations.

3. Who pays for the BTP resources that a multitenant app uses for all its tenants?
   - A. The provider, whose account the app runs in
   - B. Each consumer, through its own subaccount bill
   - C. SAP, as part of the SaaS Provisioning service
   - D. Nobody, because shared resources aren't metered

   Answer: A. SAP's documentation says the resources consumed by the app and its consumers are billed to the provider. That is why the provider's price must cover each tenant's usage.

4. Calder wants one shift-handover app for Rockford and Augsburg, and Augsburg's data must stay in the EU. What fits?
   - A. One multitenant app in the US region with two tenants
   - B. One multitenant app with Augsburg as a tenant in another region
   - C. One single-tenant app in the US region, with an EU data copy
   - D. Two deployments, one in each region, each single tenant

   Answer: D. Subscribers must sit in the provider's region, so one deployment can't serve both regions. With one data owner in each region, two single-tenant deployments are simpler than tenants.

5. A vendor says its BTP platform guarantees that tenants can't see each other's data. What should a leader ask?
   - A. Which BTP region the vendor's global account uses
   - B. How the app keeps data apart, and who tested it
   - C. Whether the vendor uses Cloud Foundry or Kyma
   - D. How many tenants the vendor already serves today

   Answer: B. The platform tells the app which tenant is calling, but the app must keep the data apart. Ask for the isolation model and the evidence that one tenant can't read another.

6. A customer of Calder's Fleet portal leaves. What must be settled before its subscription is deleted?
   - A. Nothing, because the data stays in the shared database anyway
   - B. Only the final invoice, because the platform keeps a copy
   - C. An export and retention rule, because deleting it removes the data
   - D. Only the user list, because tenants never hold their own data

   Answer: C. SAP's cockpit guide warns that deleting a subscription deletes the app's data for that subaccount. Agree an export and how long you keep it before offboarding.

7. A new release of a multitenant app is deployed. What else has to happen?
   - A. Nothing, because new code updates every tenant at once
   - B. Each tenant's database is upgraded, and failures are handled
   - C. Each tenant re-subscribes to receive the new version
   - D. SAP upgrades the tenants during its maintenance window

   Answer: B. The code is deployed once, but every tenant's database must be brought to the new schema. One tenant can fail while the rest succeed, so the run needs reporting and a retry.

## Deep layer

### Mental model

A multitenant app is **one building with many locked flats**. The code is the building: one structure, one set of pipes, one caretaker. Each tenant has a flat with its own key and its own contents. Three things make it work:

- **A front desk that knows which flat you belong to.** On BTP, the application router reads the tenant from the host name, and the login service issues a token that names the tenant.
- **Walls between the flats.** The app keeps each tenant's data apart: a database per tenant, a schema per tenant, or a shared table with a tenant column that every query must filter.
- **A move-in and move-out process.** The SaaS Provisioning service calls the app when a tenant subscribes and when it leaves, and the app builds or removes that tenant's flat.

Everything an architect decides here is one of three questions. Should this be one building with flats, or several houses? How thick are the walls? And how does a renovation (an upgrade) reach every flat when one of them is locked?

### How it works

#### The parts

SAP's Cloud Foundry guide lists the parts of a multitenant app ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/developing-multitenant-applications-in-the-cloud-foundry-environment-5e8a2b7.md)):

| Part | Where it runs | What it does |
| --- | --- | --- |
| The app | Provider subaccount | Business logic; implements the subscription callbacks |
| Application router | Provider subaccount, one per multitenant app | Single entry point; reads the tenant from the host |
| `xsuaa` instance, plan `application`, `tenant-mode: shared` | Provider subaccount | Logs users in per tenant; issues tokens naming the tenant |
| `saas-registry` instance, plan `application` | Provider subaccount | Registers the app; calls the callbacks on subscribe and unsubscribe |
| Tenant data | Database service | One store per tenant, or shared with a tenant column |
| Consumer subaccounts | Provider's global account, provider's region | One per tenant; each subscribes to the app |

```mermaid
flowchart LR
  subgraph GA[Provider's global account, one region]
    subgraph P[Provider subaccount]
      AR[Application router] --> APP[Fleet portal app]
      APP --> DB[(Tenant databases)]
      SR[saas-registry]
      UAA[xsuaa, tenant-mode shared]
    end
    B[Consumer subaccount<br/>brennock] -. subscribes .-> SR
    O[Consumer subaccount<br/>ostervale] -. subscribes .-> SR
  end
  SR -- PUT / DELETE callback --> APP
  U[Brennock user] -- brennock.fleet... --> AR
  AR -- login in Brennock's zone --> UAA
```

#### Subscribing: the callbacks

When a consumer subaccount subscribes, the SaaS Provisioning service calls the app ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/develop-the-multitenant-application-ff54047.md)):

1. **`getDependencies` (GET, optional).** The app returns the reuse services it consumes, each as an `xsappname`, so those services onboard the tenant too. Implement it only if the app has dependencies.
2. **`onSubscription` (PUT).** The URL must end in `/{tenantId}`. The body carries `subscribedTenantId`, `subscribedSubdomain`, `globalAccountGUID`, `subscriptionAppName` and a few more fields. The app creates the tenant's data store and returns **200 with the tenant's URL** as the body.
3. **`onSubscription` (DELETE).** The same URL is called when the tenant unsubscribes. The app removes what it built.

The callbacks are protected: the app's security descriptor declares a scope and grants it to `$XSAPPNAME(application,sap-provisioning,tenant-onboarding)`, so only the provisioning service can call them. If onboarding takes long (creating a database container can), set `onSubscriptionAsync` and `callbackTimeoutMillis` in the registration; past the timeout the subscription turns `FAILED` ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/register-the-multitenant-application-to-the-sap-saas-provisioning-service-3971151.md)).

```mermaid
sequenceDiagram
  participant Admin as Calder BTP admin
  participant SR as SaaS Provisioning
  participant App as Fleet portal
  participant DB as Database service
  Admin->>SR: Subscribe subaccount "brennock"
  SR->>App: GET /callback/v1.0/dependencies
  App-->>SR: [ { xsappname } ... ]
  SR->>App: PUT /callback/v1.0/tenants/{tenantId}
  App->>DB: create Brennock's database
  App-->>SR: 200 https://brennock.fleet.calder-pumpworks.example
  SR-->>Admin: Subscribed, Go to Application
```

#### Routing a request to the right tenant

SAP's approuter documentation describes the runtime path ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/configure-the-approuter-application-5af9067.md)):

1. The user opens the tenant's URL. In development the host is `<subdomain>-<approuter host>.<SAP domain>`, one route per tenant. In production it is `<subdomain>.<custom domain>`, served by one wildcard route.
2. The application router matches the host against `TENANT_HOST_PATTERN`, a regular expression whose first capturing group is the tenant's subdomain.
3. The login service finds that tenant's identity zone and its identity provider, logs the user in and issues a JSON Web Token (JWT) with the tenant, the user and the user's scopes.
4. The app reads the tenant from the validated token (SAP's Java example reads it as the user's identity zone) and opens only that tenant's data. The lab's stand-in token carries the tenant in a field it calls `zid`.

> **Note** The first label of a tenant's host may have at most 63 characters, the DNS limit. On the default domain the label is `<subdomain>-<approuter host>`, so long subdomains and long app names fail together ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/develop-the-multitenant-application-ff54047.md)).

#### Isolation models

| Model | How data is kept apart | Strength | Cost |
| --- | --- | --- | --- |
| Database (or container) per tenant | Each tenant has its own store; the app opens the tenant's store | Strongest; a forgotten filter can't leak; backup, restore and delete per tenant | More containers to create, upgrade and monitor |
| Schema per tenant | One database, one schema per tenant | Strong if connections are scoped per tenant | Schema count limits; shared database load |
| Shared table with a tenant column | Every row carries the tenant; every query filters | Cheapest at scale | One missing `WHERE tenant = ?` is a breach; one tenant's data can block a schema change for all |

CAP uses a database per tenant: locally one SQLite file per tenant, in the cloud one SAP HANA HDI container per tenant, created through SAP Service Manager or, newer, the SAP HANA Cloud Tenant Management Service v2 with the `hana-multitenancy` plan ([CAP documentation](https://cap.cloud.sap/docs/guides/multitenancy/)). The ABAP environment uses clients of one ABAP system as tenants ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/multitenancy-development-guideline-9d994c8.md)).

The database is only one wall. SAP's guide also warns that shared in-memory data (a static variable, a cache) is visible to every tenant, and that users must never run their own code in the app's process or reach its file system ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/develop-the-multitenant-application-ff54047.md)). Caches, logs, background jobs, search indexes and files all need a tenant in their key.

#### Upgrades

Deploying new code changes the app for every tenant at once, but each tenant's database still has the old schema. CAP's documentation is explicit that tenant databases must be upgraded; its recommended setup runs `cds-mtx upgrade '*'` as a Cloud Foundry hook before the new app version starts, and its job settings (`workerSize`, `clusterSize`, `queueSize`) control how many tenants upgrade in parallel ([CAP documentation](https://cap.cloud.sap/docs/guides/multitenancy/), [MTX reference](https://cap.cloud.sap/docs/guides/multitenancy/mtxs)). Two rules follow for the architect:

- **Order.** Upgrade tenant databases before the new code serves them, or keep the new code compatible with the old schema for a release.
- **Partial failure.** With fifty tenants, one will fail some day (bad data, a lock, a timeout). The process must report which tenant failed, keep the others running and retry.

#### Offboarding

The DELETE callback removes the tenant's data. SAP's cockpit guide says that deleting a subscription deletes all data related to the app in that subaccount ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/subscribe-to-multitenant-applications-using-the-cockpit-7a3e396.md)). Agree with each customer, in the contract, what is exported and how long backups are kept, and build the export before the first customer leaves.

### Build it yourself: Calder's Fleet portal, locally

You will decide which of four Calder apps need multitenancy, then run a local stand-in of the Fleet portal that onboards two water utilities, keeps their data apart, upgrades them, survives one failed upgrade and offboards one tenant. A `--weak` mode shows what breaks with a shared table. An optional step runs the same flow in real CAP on your computer.

```mermaid
flowchart LR
  D[decide] --> V[verdict per app<br/>MT01-MT04]
  R[run] --> S[subscribe callbacks]
  S --> I[tenant databases<br/>unit21/fleet/]
  R --> H[requests by host and token]
  R --> U[upgrade schema 1 to 2]
  R --> X[export, then unsubscribe]
  R --> C[checks T01-T10]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/). For the optional CAP step you also need Node.js and the CAP development kit from [Set up for Unit 5](https://erpfde.com/topics/set-up-for-unit-05/). This walkthrough doesn't repeat their steps.

> **Note** New words. A **host** is the name part of a web address, like `brennock.fleet.calder-pumpworks.example`. A **callback** is a web address your app offers so another service can call it when something happens. A **token** is a signed piece of data that says who a user is; here it also says which tenant they belong to. **SQLite** is a small database stored in one file, built into Python. A **schema** is the structure of the tables in a database. **HTTP status codes** are three-digit answers: 200 means OK, 401 not logged in, 403 not allowed, 429 too many requests, 503 not available right now.

The Calder Fleet portal, its tenants, IDs, domain and limits are course values. Calder Pumpworks and the utilities are fictional.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`.
- No account. The script uses only modules built into Python and makes no network calls.
- About 40 minutes, plus 20 for the optional CAP step. Everything is free.

#### Step 1: Open the course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. The `unit21` folder exists from the setup topic. If it doesn't, create it with `mkdir unit21`.

#### Step 2: Create the script

1. In VS Code, create a new file `unit21/tenant_lab.py`.
2. Paste the code below and save.

```python
"""Calder Fleet portal: a local stand-in for a multitenant BTP app.

Course lab for the topic "Multitenant applications on BTP" (Unit 21).
Built-in modules only, no randomness. Nothing here talks to SAP BTP:
the callbacks, host pattern and token check imitate what the SaaS
Provisioning service, the approuter and the login service do.

  python unit21/tenant_lab.py decide          which candidates need multitenancy
  python unit21/tenant_lab.py run             onboard, isolate, upgrade, offboard (checks T01-T10)
  python unit21/tenant_lab.py run --weak      same, with one shared table and a missing tenant filter
  python unit21/tenant_lab.py show            list tenants and their schema versions
  python unit21/tenant_lab.py reset           delete the lab's data folder
"""
import argparse
import json
import os
import re
import shutil
import sqlite3
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "fleet")              # tenant databases, registry, exports
REGISTRY = os.path.join(DATA, "tenants.json")

# ---- course values (all fictional) ----------------------------------------
PROVIDER_REGION = "us10"
APP_NAME = "calder-fleet"
DOMAIN = "fleet.calder-pumpworks.example"       # custom domain with a wildcard route
TENANT_HOST_PATTERN = r"^(.*)\." + re.escape(DOMAIN) + r"$"
APP_SCHEMA_VERSION = 2                          # the code being deployed expects schema 2
RATE_LIMIT_PER_MIN = 120                        # course limit per tenant
UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")

SUBSCRIPTIONS = [  # what the SaaS Provisioning service would send (field names from SAP's docs)
    {"subscribedTenantId": "6f1c2a40-5b7e-4c1d-9a20-10000001aa01", "subscribedSubdomain": "brennock",
     "subscriptionAppName": APP_NAME, "globalAccountGUID": "calder-ga", "region": "us10"},
    {"subscribedTenantId": "8d3e4b52-7c9f-4e2a-8b31-10000021bb02", "subscribedSubdomain": "ostervale",
     "subscriptionAppName": APP_NAME, "globalAccountGUID": "calder-ga", "region": "us10"},
]
TOO_LONG = {"subscribedTenantId": "1a2b3c4d-0000-4000-8000-000000000003",
            "subscribedSubdomain": "lindmoor-district-water-and-wastewater-authority-north-and-east-sector",
            "subscriptionAppName": APP_NAME, "globalAccountGUID": "calder-ga", "region": "us10"}
WRONG_REGION = {"subscribedTenantId": "1a2b3c4d-0000-4000-8000-000000000004",
                "subscribedSubdomain": "auental", "subscriptionAppName": APP_NAME,
                "globalAccountGUID": "calder-ga", "region": "eu10"}

PUMPS = {  # each utility's own pumps (made up; serials from the course scenarios)
    "brennock": [("RK2611-0041", "ES-200", "Lift station 4", "2027-11-01"),
                 ("RK2611-0042", "ES-200", "Lift station 4", "2027-11-01"),
                 ("RK2611-0043", "ES-200", "Lift station 7", "2027-11-01"),
                 ("RK2611-0044", "ES-200", "Lift station 2", "2027-11-01")],
    "ostervale": [("RK2609-0017", "ES-200", "Pump station 1", "2027-09-15"),
                  ("RK2609-0018", "ES-200", "", "2027-09-15")],   # site left blank: upgrade 2 trips on it
}

CANDIDATES = [  # MT01-MT04; the exercise adds MT05
    {"id": "MT01", "name": "Fleet portal for water utilities", "data_owners": "many",
     "tenants_expected": 25, "same_code_for_all": True, "provider_operates": True, "regions": ["us10"],
     "note": "each utility sees only its own Calder pumps, warranty and service visits"},
    {"id": "MT02", "name": "Distributor order-status app (R03)", "data_owners": "one",
     "tenants_expected": 1, "same_code_for_all": True, "provider_operates": True, "regions": ["us10"],
     "note": "the data is Calder's own orders; distributors are users, filtered by customer"},
    {"id": "MT03", "name": "Shift handover for Rockford and Augsburg", "data_owners": "one",
     "tenants_expected": 2, "same_code_for_all": True, "provider_operates": True, "regions": ["us10", "eu10"],
     "note": "one company group; Augsburg's data stays in the EU"},
    {"id": "MT04", "name": "Test certificate archive (W06)", "data_owners": "one",
     "tenants_expected": 1, "same_code_for_all": True, "provider_operates": True, "regions": ["us10"],
     "note": "both company codes in one archive; company code is a field, not a tenant"},
]


def decide(c):
    """Course rules, in order. Returns (verdict, reason)."""
    if len(c["regions"]) > 1:
        return "SEPARATE DEPLOYMENTS", "subscribers must be in the provider's region: deploy once per region"
    if c["data_owners"] != "many":
        return "SINGLE TENANT", "one data owner: separate users with authorizations, not tenants"
    if not c["provider_operates"]:
        return "SINGLE TENANT PER CUSTOMER", "customers run it themselves, so there is no shared operation to gain"
    if not c["same_code_for_all"]:
        return "SINGLE TENANT PER CUSTOMER", "tenants need their own code or release"
    if c["tenants_expected"] < 3:
        return "SINGLE TENANT PER CUSTOMER", "fewer than 3 tenants: the tenant machinery costs more than it saves"
    return "MULTITENANT", "many owners, one code line, one operator, one region"


# ---- the provider app ------------------------------------------------------
class FleetApp:
    def __init__(self, weak=False):
        self.weak = weak                # True: one shared table, and the read forgets the tenant filter
        os.makedirs(DATA, exist_ok=True)
        self.tenants = json.load(open(REGISTRY)) if os.path.exists(REGISTRY) else {}
        self.calls = {}

    def save(self):
        with open(REGISTRY, "w") as f:
            json.dump(self.tenants, f, indent=2)

    def db_path(self, tenant_id):
        if not UUID_RE.match(tenant_id):
            raise ValueError("tenant ID is not a UUID")      # never build a path from an unchecked ID
        name = "shared.sqlite" if self.weak else f"tenant-{tenant_id}.sqlite"
        return os.path.join(DATA, name)

    # PUT /callback/v1.0/tenants/{tenantId}
    def on_subscribe(self, tenant_id, payload):
        sub = payload["subscribedSubdomain"]
        if payload.get("region") != PROVIDER_REGION:
            return 400, f"subscriber region {payload.get('region')} differs from provider region {PROVIDER_REGION}"
        if len(sub) > 63:
            return 400, f"subdomain has {len(sub)} characters; a DNS label allows 63"
        con = sqlite3.connect(self.db_path(tenant_id))
        if self.weak:
            con.execute("CREATE TABLE IF NOT EXISTS pumps (tenant TEXT, serial TEXT, model TEXT, site TEXT, warranty_to TEXT)")
        else:
            con.execute("CREATE TABLE IF NOT EXISTS pumps (serial TEXT PRIMARY KEY, model TEXT, site TEXT, warranty_to TEXT)")
        for row in PUMPS.get(sub, []):
            if self.weak:
                con.execute("INSERT INTO pumps VALUES (?,?,?,?,?)", (tenant_id,) + row)
            else:
                con.execute("INSERT OR REPLACE INTO pumps VALUES (?,?,?,?)", row)
        con.commit()
        con.close()
        self.tenants[tenant_id] = {"subdomain": sub, "schema": 1, "status": "SUBSCRIBED"}
        self.save()
        return 200, f"https://{sub}.{DOMAIN}"          # the body is the tenant's URL

    # DELETE /callback/v1.0/tenants/{tenantId}
    def on_unsubscribe(self, tenant_id, exported=False):
        if tenant_id not in self.tenants:
            return 404, "unknown tenant"
        if not exported:
            return 409, "course rule: export the tenant's data before it is deleted"
        if not self.weak:
            os.remove(self.db_path(tenant_id))
        del self.tenants[tenant_id]
        self.save()
        return 200, "tenant data deleted"

    def export(self, tenant_id):
        con = sqlite3.connect(self.db_path(tenant_id))
        rows = con.execute("SELECT * FROM pumps").fetchall()
        con.close()
        path = os.path.join(DATA, f"export-{self.tenants[tenant_id]['subdomain']}.json")
        with open(path, "w") as f:
            json.dump(rows, f, indent=2)
        return path

    # what the approuter and the app do on every request
    def handle(self, host, token, minute=0):
        m = re.match(TENANT_HOST_PATTERN, host)
        if not m:
            return 404, "host does not match TENANT_HOST_PATTERN"
        sub = m.group(1)
        tenant_id = next((t for t, v in self.tenants.items() if v["subdomain"] == sub), None)
        if tenant_id is None:
            return 404, f"no subscription for {sub}"
        if not token or "zid" not in token:
            return 401, "no token or no tenant in the token"
        if token["zid"] != tenant_id:
            return 403, "token's tenant (zid) differs from the host's tenant"
        key = (tenant_id, minute)
        self.calls[key] = self.calls.get(key, 0) + 1
        if self.calls[key] > RATE_LIMIT_PER_MIN:
            return 429, "tenant over its request limit"
        if self.tenants[tenant_id]["schema"] < APP_SCHEMA_VERSION:
            return 503, f"tenant on schema {self.tenants[tenant_id]['schema']}, app needs {APP_SCHEMA_VERSION}: upgrade first"
        con = sqlite3.connect(self.db_path(tenant_id))
        if self.weak:
            rows = con.execute("SELECT serial FROM pumps").fetchall()   # the bug: no WHERE tenant = ?
        else:
            rows = con.execute("SELECT serial FROM pumps").fetchall()   # the database holds one tenant only
        con.close()
        return 200, sorted(r[0] for r in rows)

    # what cds-mtx upgrade does per tenant, in this stand-in: schema 1 -> 2
    def upgrade(self, tenant_id):
        t = self.tenants[tenant_id]
        if t["schema"] >= APP_SCHEMA_VERSION:
            return "already current"
        con = sqlite3.connect(self.db_path(tenant_id))
        blank = con.execute("SELECT serial FROM pumps WHERE site = ''").fetchall()
        if blank:
            con.close()
            t["status"] = "UPGRADE_FAILED"
            self.save()
            return f"failed: pump {blank[0][0]} has no site (schema 2 makes site mandatory)"
        cols = [r[1] for r in con.execute("PRAGMA table_info(pumps)")]
        if "last_service" not in cols:
            con.execute("ALTER TABLE pumps ADD COLUMN last_service TEXT")
        con.commit()
        con.close()
        t["schema"], t["status"] = APP_SCHEMA_VERSION, "SUBSCRIBED"
        self.save()
        return "upgraded to schema 2"


def run(weak):
    reset(quiet=True)
    app = FleetApp(weak=weak)
    b, o = SUBSCRIPTIONS[0]["subscribedTenantId"], SUBSCRIPTIONS[1]["subscribedTenantId"]
    results = []

    def check(cid, text, ok, detail):
        results.append(ok)
        print(f"{cid}  {'OK  ' if ok else 'FAIL'}  {text}: {detail}")

    for cid, p in (("T01", SUBSCRIPTIONS[0]), ("T02", SUBSCRIPTIONS[1])):
        code, body = app.on_subscribe(p["subscribedTenantId"], p)
        check(cid, f"subscribe {p['subscribedSubdomain']}", code == 200, f"{code} {body}")
    code, body = app.on_subscribe(TOO_LONG["subscribedTenantId"], TOO_LONG)
    check("T03", "refuse a subdomain over 63 characters", code == 400, f"{code} {body}")
    code, body = app.on_subscribe(WRONG_REGION["subscribedTenantId"], WRONG_REGION)
    check("T04", "refuse a subscriber in another region", code == 400, f"{code} {body}")

    print("     -- upgrade 2 is deployed: the code now expects schema 2 --")
    code, body = app.handle(f"brennock.{DOMAIN}", {"zid": b})
    check("T05", "serve no tenant whose schema is behind the code", code == 503, f"{code} {body}")
    up_b, up_o = app.upgrade(b), app.upgrade(o)
    check("T06", "upgrade every tenant, report the one that fails",
          up_b.startswith("upgraded") and up_o.startswith("failed"), f"brennock {up_b}; ostervale {up_o}")
    con = sqlite3.connect(app.db_path(o))                   # Ostervale's admin fills in the site
    con.execute("UPDATE pumps SET site = 'Pump station 2' WHERE serial = 'RK2609-0018'")
    con.commit()
    con.close()
    resumed = [f"{app.tenants[t]['subdomain']} {app.upgrade(t)}" for t in (b, o)
               if app.tenants[t]["status"] == "UPGRADE_FAILED"]
    print(f"     -- ostervale fixes its data; the upgrade resumes for failed tenants: {'; '.join(resumed)} --")

    code, body = app.handle(f"brennock.{DOMAIN}", {"zid": b})
    mine = code == 200 and body == sorted(r[0] for r in PUMPS["brennock"])
    check("T07", "Brennock sees only Brennock's pumps", mine, f"{code} {body}")
    code, body = app.handle(f"ostervale.{DOMAIN}", {"zid": b})
    check("T08", "Brennock's token on Ostervale's URL is refused", code == 403, f"{code} {body}")
    codes = [app.handle(f"brennock.{DOMAIN}", {"zid": b}, minute=5)[0] for _ in range(150)]
    other = [app.handle(f"ostervale.{DOMAIN}", {"zid": o}, minute=5)[0] for _ in range(10)]
    check("T09", "one tenant's flood doesn't block another",
          codes.count(429) == 30 and other.count(200) == 10,
          f"brennock {codes.count(200)} served, {codes.count(429)} refused; ostervale {other.count(200)} of 10 served")
    code, body = app.on_unsubscribe(o)
    first = f"{code} {body}"
    path = app.export(o)
    code, body = app.on_unsubscribe(o, exported=True)
    check("T10", "offboard only after an export", first.startswith("409") and code == 200,
          f"first try {first}; after export to {os.path.relpath(path, HERE)}: {code} {body}")

    passed = sum(results)
    print(f"\n{passed} of {len(results)} checks OK" + ("  (weak mode: shared table, missing tenant filter)" if weak else ""))
    return 0 if passed == len(results) else 1


def show():
    app = FleetApp()
    if not app.tenants:
        print("No tenants. Run: python unit21/tenant_lab.py run")
        return
    print(f"{'tenant ID':38} {'subdomain':12} schema  status")
    for tid, t in app.tenants.items():
        print(f"{tid:38} {t['subdomain']:12} {t['schema']:<7} {t['status']}")


def reset(quiet=False):
    if os.path.isdir(DATA):
        shutil.rmtree(DATA)
    if not quiet:
        print(f"Deleted {DATA}")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("command", choices=["decide", "run", "show", "reset"])
    ap.add_argument("--weak", action="store_true", help="shared table with a missing tenant filter")
    a = ap.parse_args()
    if a.command == "decide":
        for c in CANDIDATES:
            verdict, why = decide(c)
            print(f"{c['id']}  {verdict:27} {c['name']}\n      {why}")
        return 0
    if a.command == "run":
        return run(a.weak)
    if a.command == "show":
        show()
    else:
        reset()
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

#### Step 3: Decide which apps need multitenancy

1. Run:

   ```bash
   python unit21/tenant_lab.py decide
   ```

2. You should see:

   ```text
   MT01  MULTITENANT                 Fleet portal for water utilities
         many owners, one code line, one operator, one region
   MT02  SINGLE TENANT               Distributor order-status app (R03)
         one data owner: separate users with authorizations, not tenants
   MT03  SEPARATE DEPLOYMENTS        Shift handover for Rockford and Augsburg
         subscribers must be in the provider's region: deploy once per region
   MT04  SINGLE TENANT               Test certificate archive (W06)
         one data owner: separate users with authorizations, not tenants
   ```

Only one of Calder's four apps earns the tenant machinery. The rules are course rules, in a fixed order; the region rule comes first because a single deployment can't serve two regions whatever else is true. The threshold of three tenants is a course value; set your own from what onboarding and upgrades cost you.

#### Step 4: Run the tenant lifecycle

1. Run:

   ```bash
   python unit21/tenant_lab.py run
   ```

2. You should see ten checks, all OK:

   ```text
   T01  OK    subscribe brennock: 200 https://brennock.fleet.calder-pumpworks.example
   T02  OK    subscribe ostervale: 200 https://ostervale.fleet.calder-pumpworks.example
   T03  OK    refuse a subdomain over 63 characters: 400 subdomain has 70 characters; a DNS label allows 63
   T04  OK    refuse a subscriber in another region: 400 subscriber region eu10 differs from provider region us10
        -- upgrade 2 is deployed: the code now expects schema 2 --
   T05  OK    serve no tenant whose schema is behind the code: 503 tenant on schema 1, app needs 2: upgrade first
   T06  OK    upgrade every tenant, report the one that fails: brennock upgraded to schema 2; ostervale failed: pump RK2609-0018 has no site (schema 2 makes site mandatory)
        -- ostervale fixes its data; the upgrade resumes for failed tenants: ostervale upgraded to schema 2 --
   T07  OK    Brennock sees only Brennock's pumps: 200 ['RK2611-0041', 'RK2611-0042', 'RK2611-0043', 'RK2611-0044']
   T08  OK    Brennock's token on Ostervale's URL is refused: 403 token's tenant (zid) differs from the host's tenant
   T09  OK    one tenant's flood doesn't block another: brennock 120 served, 30 refused; ostervale 10 of 10 served
   T10  OK    offboard only after an export: first try 409 course rule: export the tenant's data before it is deleted; after export to fleet/export-ostervale.json: 200 tenant data deleted

   10 of 10 checks OK
   ```

3. Look in `unit21/fleet/`. You'll find `tenant-6f1c2a40-....sqlite` for Brennock, `tenants.json` (the registry) and `export-ostervale.json`. Ostervale's database is gone; its export stayed.
4. Run `python unit21/tenant_lab.py show` to list the tenants still subscribed.

> **Note** The tenants, pumps, limits and results come from made-up data. They show the method, not results from a real SAP BTP system. The script has no randomness, so your output should match line for line.

What each check teaches:

- **T01 to T04, onboarding.** The PUT callback returns the tenant's URL. It refuses what would fail later anyway: a host label over 63 characters, and a subscriber outside the provider's region.
- **T05 and T06, upgrades.** The new code refuses to serve a tenant still on the old schema, rather than failing halfway through a request. One tenant's upgrade fails on its own data; the other tenant is upgraded and keeps working.
- **T07 and T08, isolation.** Brennock reads only its four pumps, and Brennock's token used on Ostervale's address is refused, because the tenant in the token must match the tenant in the host.
- **T09, noisy neighbors.** A per-tenant limit stops one utility's runaway script without slowing the other.
- **T10, offboarding.** Data is deleted only after an export.

#### Step 5: Break it on purpose with a shared table

1. Run:

   ```bash
   python unit21/tenant_lab.py run --weak
   ```

2. Two checks now fail:

   ```text
   T06  FAIL  upgrade every tenant, report the one that fails: brennock failed: pump RK2609-0018 has no site (schema 2 makes site mandatory); ostervale failed: pump RK2609-0018 has no site (schema 2 makes site mandatory)
   T07  FAIL  Brennock sees only Brennock's pumps: 200 ['RK2609-0017', 'RK2609-0018', 'RK2611-0041', 'RK2611-0042', 'RK2611-0043', 'RK2611-0044']
   ```

   and the last line reads `8 of 10 checks OK  (weak mode: shared table, missing tenant filter)`.

Weak mode keeps every tenant in one table with a tenant column, and the read forgets `WHERE tenant = ?`. **T07** is the breach: Brennock sees Ostervale's pumps. **T06** is the quieter cost: Ostervale's blank site blocks Brennock's upgrade too, because a schema change on a shared table must suit every tenant's rows. Notice that T08 still passes: the token check at the door was fine, and the leak happened inside. That is why isolation needs tests at the data layer, not only at login.

Run `python unit21/tenant_lab.py run` again to go back to the strong version.

#### Step 6 (optional): The same flow in real CAP

This step runs CAP's own multitenancy on your computer, with one SQLite database per tenant. It needs Node.js and `@sap/cds-dk` from [Set up for Unit 5](https://erpfde.com/topics/set-up-for-unit-05/), and an internet connection for `npm install`. It was tested in this run with `@sap/cds-dk` 10.2.1, `@sap/cds` 10.2.2 and `@sap/cds-mtxs` 4.2.2 on Node.js 22.

1. In the terminal, from your course folder:

   ```bash
   cd unit21
   cds init fleet-portal
   cd fleet-portal
   cds add nodejs
   ```

2. Create `db/schema.cds`:

   ```cds
   namespace calder.fleet;
   entity Pumps {
     key serial : String(20);
     model      : String(10);
     site       : String(40);
     status     : String(10);
   }
   ```

3. Create `srv/fleet-service.cds`:

   ```cds
   using calder.fleet as f from '../db/schema';
   service FleetService {
     entity Pumps as projection on f.Pumps;
   }
   ```

4. Create `db/data/calder.fleet-Pumps.csv` with these two lines (CAP loads it into every new tenant):

   ```text
   serial;model;site;status
   DEMO-0001;ES-200;Demo site;RUNNING
   ```

5. Add multitenancy and install the libraries for the app and for the MTX sidecar:

   ```bash
   cds add multitenancy
   npm install
   cd mtx/sidecar
   npm install
   cd ../..
   ```

   `npm` may warn that the sidecar asks for Node.js 24 (`EBADENGINE`). On Node.js 22 the local test still ran.

6. Open a second terminal (**Terminal > New Terminal**), go to `unit21/fleet-portal` and start the sidecar, which handles subscriptions:

   ```bash
   cds watch mtx/sidecar
   ```

   Wait for `server listening on { url: 'http://localhost:4005' }`.

7. Open a third terminal, go to `unit21/fleet-portal` and start the app:

   ```bash
   cds watch --with-mtx
   ```

   Wait for `server listening on { url: 'http://localhost:4004' }`.

8. Back in the first terminal, subscribe two tenants. CAP's built-in test users `alice` belongs to tenant `t1` and `erin` to `t2`:

   ```bash
   cds subscribe t1 --to http://localhost:4005
   cds subscribe t2 --to http://localhost:4005
   ```

   Each prints `Subscribe successful.`, and files `db-t1.sqlite` and `db-t2.sqlite` appear, one per tenant.

9. Add a pump in tenant `t1` as `alice`:

   - **Windows (PowerShell):**

     ```powershell
     $a = @{ Authorization = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("alice:")) }
     Invoke-RestMethod -Method Post -Uri http://localhost:4004/odata/v4/fleet/Pumps -Headers $a -ContentType "application/json" -Body '{"serial":"RK2611-0041","model":"ES-200","site":"Lift station 4","status":"RUNNING"}'
     ```

   - **macOS / Linux:**

     ```bash
     curl -s -u alice: -X POST http://localhost:4004/odata/v4/fleet/Pumps -H 'Content-Type: application/json' -d '{"serial":"RK2611-0041","model":"ES-200","site":"Lift station 4","status":"RUNNING"}'
     ```

10. Read the pumps as each user. On Windows use `Invoke-RestMethod -Uri http://localhost:4004/odata/v4/fleet/Pumps -Headers $a` for `alice`, and build `$e` the same way with `"erin:"`. On macOS or Linux:

    ```bash
    curl -s -u alice: http://localhost:4004/odata/v4/fleet/Pumps
    curl -s -u erin: http://localhost:4004/odata/v4/fleet/Pumps
    ```

    `alice` sees `DEMO-0001` and `RK2611-0041`; `erin` sees only `DEMO-0001`. Same app, two databases.

11. Try an upgrade. Add a line `warrantyTo : Date;` to the `Pumps` entity in `db/schema.cds` and save. Stop the sidecar (**Ctrl+C** in its terminal) and start it again with `cds watch mtx/sidecar`, so it loads the new model. Then:

    ```bash
    cds upgrade t1 --at http://localhost:4005 -u yves:
    ```

    Reading as `alice` now works and shows `warrantyTo`. Reading as `erin` fails with `no such column` until you run the same command for `t2`. That is check T05 from the stand-in, in real CAP: the new code is live for both tenants, but only one database has caught up.

12. Unsubscribe one tenant with `cds unsubscribe t2 --from http://localhost:4005`. Its file `db-t2.sqlite` is deleted, data and all.

13. Stop both servers with **Ctrl+C**.

> **Note** In this run, `cds upgrade '*'` against the local sidecar address didn't upgrade all tenants; it created a file named `db-*.sqlite`. Upgrade local tenants by name. In the cloud, CAP's documented way to upgrade all tenants is `cds-mtx upgrade '*'`, run from the sidecar as a deployment hook ([CAP documentation](https://cap.cloud.sap/docs/guides/multitenancy/)).

#### Step 7: Write the decision record

1. Create `unit21/fleet_portal_adr.md` and copy in the ADR from **Architecture view** below, adjusted to your own verdicts from Step 3.
2. Add one line per check from Step 4 under a heading *Evidence*, so a reviewer sees what was tested.
3. Save your work with Git:

   ```bash
   git add unit21/tenant_lab.py unit21/fleet_portal_adr.md
   git commit -m "Unit 21: multitenancy decision and tenant lab"
   ```

   Don't commit `unit21/fleet/` or `unit21/fleet-portal/node_modules/`; they are generated.

#### How the code works

| Part of the script | What it does |
| --- | --- |
| `CANDIDATES` and `decide()` | Four Calder apps and the course rules that give each a verdict |
| `SUBSCRIPTIONS`, `TOO_LONG`, `WRONG_REGION` | The bodies the SaaS Provisioning service would send, with SAP's field names |
| `db_path()` | Builds the tenant's database file name, refusing a tenant ID that isn't a UUID |
| `on_subscribe()` | Stands in for the PUT callback: checks region and host label, creates the tenant's database, returns its URL |
| `on_unsubscribe()` and `export()` | Stand in for the DELETE callback; delete only after an export |
| `handle()` | Stands in for the approuter and the app: tenant from host, tenant from token, rate limit, schema version, then the read |
| `upgrade()` | Stands in for a per-tenant schema upgrade; fails on bad data instead of half-changing |
| `run()` | Runs checks T01 to T10 in order and prints the result |
| `--weak` | One shared table with a tenant column, and a read without the tenant filter |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on your path, or the virtual environment is off | Turn on `.venv` (Step 1); on macOS or Linux try `python3` |
| `ModuleNotFoundError` | A file name or Python version problem; the script uses built-in modules only | Check the file is `unit21/tenant_lab.py` and Python is 3.10 or newer |
| `can't open file ... tenant_lab.py` | You're not in the course folder | `cd` to `orchestrate-course` and run again |
| Fewer than 10 checks OK without `--weak` | The code was changed or pasted incompletely | Paste the script again; then run `reset` and `run` |
| `cds: command not found` (Step 6) | The CAP development kit isn't installed | Follow [Set up for Unit 5](https://erpfde.com/topics/set-up-for-unit-05/) |
| `npm install` hangs or fails with a network error | No internet, or a company proxy blocks the npm registry | Try another network, or ask IT for the proxy settings for npm; Steps 1 to 5 don't need it |
| `EADDRINUSE` on port 4004 or 4005 | A server from an earlier try is still running | Stop it with **Ctrl+C** in its terminal, or close that terminal |
| `no such column` for a tenant | That tenant's database hasn't been upgraded to the new model | Restart the sidecar after model changes, then `cds upgrade <tenant>` |

### The SAP way

As of November 2026, SAP offers three routes to a multitenant app on BTP:

- **Cloud Foundry, built by hand.** You implement the callbacks, create an `xsuaa` instance with `tenant-mode: shared` and an `saas-registry` instance with the `application` plan, deploy an application router with `TENANT_HOST_PATTERN`, and bind it all together; SAP's guide walks through the six steps ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/developing-multitenant-applications-in-the-cloud-foundry-environment-5e8a2b7.md)). The registration can define `appPlans` (visible only to subaccounts of the provider's global account) and which plans a subscription may switch to ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/register-the-multitenant-application-to-the-sap-saas-provisioning-service-3971151.md)).
- **CAP with MTX.** For CAP itself as an architect sees it, see [CAP in depth for architects](https://erpfde.com/topics/cap-for-architects/). `cds add multitenancy` adds `@sap/cds-mtxs` and a sidecar that serves the provisioning, deployment and model services; tenant databases are HDI containers created through SAP Service Manager or the SAP HANA Cloud Tenant Management Service v2. CAP warns to use only the `hana-multitenancy` plan with TMS v2, because other plans can expose other applications' data. CAP also registers SaaS dependencies for services such as audit log, connectivity, destinations, the HTML5 application repository and the portal ([CAP documentation](https://cap.cloud.sap/docs/guides/multitenancy/)). On Kyma, the CAP Operator, an SAP open-source Kubernetes operator, automates tenant operations for multitenant CAP apps on Kubernetes clusters, primarily Gardener-managed ones ([SAP on GitHub](https://github.com/SAP/cap-operator)).
- **ABAP environment.** An add-on product plus the ABAP Solution service and the Landscape Portal. Tenants are clients; a setting `consumer_tenant_limit` decides whether each subscription gets a new ABAP system or a client in a shared one; subscription-based multitenancy works only in test and production systems, not in development systems ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/multitenant-applications-195031f.md)). SAP's guideline says isolation isn't fully ensured by the infrastructure and proposes an external audit where strict isolation is a legal requirement ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/multitenancy-development-guideline-9d994c8.md)).

Operations tools: subscriptions are created in the cockpit, with `btp subscribe accounts/subaccount` in the btp CLI ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/working-with-multitenant-applications-using-the-btp-cli-c1b0fcc.md)), or with the SaaS Provisioning APIs on the SAP Business Accelerator Hub. The subscription management dashboard shows every subscription with its status and errors, updates dependencies in bulk, and is opened by users with the roles *Subscription Management Dashboard Administrator* or *Viewer* ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/using-the-sap-btp-subscription-management-dashboard-434be69.md)). For production, SAP recommends a custom domain with a wildcard route, so no route is created per tenant ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/using-a-custom-domain-for-the-multitenant-application-c52ca39.md)).

**Licensing.** The provider's global account pays for what the app and its tenants consume. Consumer subaccounts must be entitled to the app before they can subscribe ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/subscribe-to-multitenant-applications-using-the-cockpit-7a3e396.md)). For ABAP SaaS sold to customers, SAP points to registering the solution in the SAP Store ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/commercialize-57c19c7.md)). The commercial terms for selling a multitenant app to other companies are partner terms; confirm them with SAP.

### Build vs. SAP

| Need | Build by hand (Cloud Foundry) | CAP with MTX | ABAP environment |
| --- | --- | --- | --- |
| Team skills | Any runtime language; you write the callbacks | CAP in Node.js or Java | ABAP Cloud |
| Tenant data | Your choice; you build and test isolation | Database per tenant, managed by MTX | Client per tenant in a shared system, or a system per tenant |
| Upgrades | You write the tenant loop and its error handling | `cds-mtx upgrade` with job settings | Add-on updates through the Landscape Portal |
| Tenant-specific extensions | You build them | Supported by the extensibility service | Limited; consumers can't extend with development tools |
| When it fits | A non-CAP stack, or very unusual isolation needs | Most new BTP SaaS apps | Reusing ABAP skills or code for SaaS |
| What it doesn't fix | Your own bugs in isolation | Shared caches and files in your code | Isolation in AMDP and client-independent tables |

### Architecture view

**Where it sits.** The Fleet portal is a side-by-side app in its own directory of Calder's global account, region `us10`: one provider subaccount `calder-fleet-prod` and one consumer subaccount per utility, created by Calder. It reads installed-base data (Calder's equipment records for pumps at customers, from the maintenance topics) from `CP10`'s S/4HANA through the connectivity set up in [Connectivity](https://erpfde.com/topics/btp-connectivity/). Each tenant gets only its own pumps. The diagram in **How it works** shows the BTP side.

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Tenant isolation | Zero cross-tenant reads, tested on every release | A data breach across customers |
| Onboarding time | Under 15 minutes from contract to URL (course target) | Sales promises slip; manual steps creep in |
| Upgrade completion | All tenants upgraded before the new code serves them | Errors for every tenant left behind |
| Noisy neighbors | Per-tenant request limit (course: 120 a minute) | One tenant's script slows all the others |
| Data residency | One region per deployment | Customers who need another region can't subscribe |
| Cost per tenant | Known and covered by the price | Every new customer loses money |

**Integration and identity.** Users arrive through the custom domain, the application router reads the tenant from the host, and each tenant's subaccount trusts that utility's own identity provider, so Calder doesn't manage the utilities' passwords (see [The BTP security model](https://erpfde.com/topics/btp-security-model/)). Calls to S/4HANA use one technical connection for the app, so the app itself must filter installed-base data by the tenant's customer number; that mapping (tenant to customer `10000001` and so on) is set at onboarding and is part of isolation.

**The decision to record.**

- **Context.** Calder wants a Fleet portal for about 25 water utilities. Each must see only its own pumps. Calder runs it centrally, in the US region.
- **Options.** A: one single-tenant app with authorizations per utility. B: a multitenant CAP app with a database per tenant. C: a single-tenant deployment per utility.
- **Decision.** B. Each utility is a separate data owner, which rules out A's shared data for contractual reasons; C multiplies deployments and upgrades by 25.
- **Consequences.** Calder builds an onboarding runbook (subaccount, entitlement, subscription, trust, customer mapping), runs tenant upgrades as a deployment step with a report of failures, keeps an export per tenant before offboarding, and pays for all tenants' usage, which the service price must cover. EU customers would need a second deployment.

**What a design review will ask.**

1. How do you prove one tenant can't read another's data, and does that test run on every release?
2. What happens to the tenants whose upgrade fails, and who is told?
3. Where else is tenant data kept: caches, logs, files, search indexes, AI prompts?
4. What does onboarding cost per tenant, and which steps are still manual?
5. What do you give a customer when it leaves, and when is its data really gone?

### Production concerns

- **Security and authorizations.** Check the tenant twice: in the host and in the token, and refuse any mismatch. Never build a file path or database name from an unchecked tenant ID. Put the tenant into every cache key, log line and background job. SAP's guide adds: no user code in the app's process and no user access to its file system.
- **Evaluation.** Keep an isolation test suite like T07 and T08, with at least two tenants, and run it in the pipeline. Add a test that reads each table with a token of the wrong tenant.
- **Cost.** Each database container and each sidecar instance costs money, and the provider pays for all of them. Track usage per tenant; CAP's job settings and the sidecar's size decide how fast upgrades run across many tenants.
- **Operations.** Watch the subscription management dashboard for `FAILED` subscriptions. Run tenant upgrades as part of deployment, and alert on any tenant left behind. Use blue-green deployment for the app, as SAP recommends for multitenant MTAs on a custom domain.
- **Clean core.** The Fleet portal reads S/4HANA through released APIs and keeps its own data on BTP, so it adds nothing to S/4HANA's core. Tenant mapping to customer numbers lives in the portal, not in S/4HANA.

### Where AI fits

Multitenancy matters more, not less, once agents are involved:

- **An agent in a multitenant app must carry the tenant everywhere.** Every tool call, retrieval and memory read needs the tenant from the user's token, never from the prompt. A tenant ID that the model can write is an injection path. [Agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) covers passing the user's identity to tools.
- **Memories and indexes are tenant data.** A vector index or an agent's memory shared across tenants is the same risk as a shared table without a filter. Key them by tenant, as in [Agent memory and long-running agents](https://erpfde.com/topics/agent-memory-and-long-running-agents/).
- **Model costs belong to a tenant.** Put the tenant on every model call's usage record, so cost per tenant includes AI, and so a per-tenant limit can stop a runaway agent the way T09 stops a runaway script. [AI gateways](https://erpfde.com/topics/ai-gateways-for-model-and-agent-traffic/) shows where to meter.

As far as this run could find, SAP's multitenancy documentation describes no AI feature for tenant management as of 27 November 2026.

### Pitfalls

- **Making an internal app multitenant.** Plants, company codes and distributors are data dimensions inside one company; tenants for them add cost and process.
- **Trusting the platform for isolation.** The platform names the tenant; your code keeps the data apart.
- **A shared table without a tested filter.** One missing condition leaks every tenant, and one tenant's data can block everyone's schema change.
- **Tenant data outside the database.** Static variables, caches, temporary files and logs shared across tenants.
- **Upgrading the code but not the tenants.** New code meets old schemas and fails for everyone not yet upgraded.
- **No plan for a failed tenant upgrade.** The loop stops at tenant 17 of 50, and nobody knows which are done.
- **Long names.** `<subdomain>-<app host>` over 63 characters breaks the route on the default domain.
- **Offboarding without an export.** Deleting the subscription deletes the data.
- **Forgetting the region.** Subscribers must be in the provider's region; a customer in another region needs another deployment.

### Exercise

Calder's service manager proposes a second portal: independent repair shops that service Calder pumps would each see only their own repair jobs. A third utility, the Town of Harwell, also signs up for the Fleet portal.

1. Open `unit21/tenant_lab.py`.
2. Add a fifth candidate to `CANDIDATES`, after `MT04`:

   ```python
       {"id": "MT05", "name": "Repair-shop portal for service partners", "data_owners": "many",
        "tenants_expected": 6, "same_code_for_all": True, "provider_operates": True, "regions": ["us10"],
        "note": "each independent repair shop sees only its own repair jobs"},
   ```

3. Run `python unit21/tenant_lab.py decide` and note the verdict. Change `tenants_expected` to 2, run again, and write down why the verdict changes. Set it back to 6.
4. Add Harwell's pump to `PUMPS`:

   ```python
       "harwell": [("RK2612-0051", "ES-200", "Well field pump house", "2027-12-10")],
   ```

5. In `run()`, just before the line `passed = sum(results)`, add two checks:

   ```python
       h = "3c5d6e7f-1a2b-4c3d-8e9f-000000000005"
       app.on_subscribe(h, {"subscribedTenantId": h, "subscribedSubdomain": "harwell",
                            "subscriptionAppName": APP_NAME, "globalAccountGUID": "calder-ga",
                            "region": "us10"})
       app.upgrade(h)
       code, body = app.handle(f"harwell.{DOMAIN}", {"zid": h}, minute=6)
       check("T11", "a new tenant sees only its own pump", code == 200 and body == ["RK2612-0051"], f"{code} {body}")
       code, body = app.handle(f"brennock.{DOMAIN}", {"zid": h}, minute=6)
       check("T12", "Harwell's token on Brennock's URL is refused", code == 403, f"{code} {body}")
   ```

6. Run `python unit21/tenant_lab.py run`, then `python unit21/tenant_lab.py run --weak`, and record which checks fail in weak mode and why.
7. Add MT05's verdict and the two new checks to `unit21/fleet_portal_adr.md`. This file goes into your architect pack for the capstone in Unit 32.

**Done when:** `decide` prints `MT05  MULTITENANT` for six repair shops, `run` ends with `12 of 12 checks OK`, and your ADR names which checks fail with `--weak` and what each failure would mean for Calder's customers.

### Check yourself

1. In the Fleet portal, where does the app learn which tenant a request belongs to?
   - A. From a tenant field that the browser sends in the request body
   - B. From the consumer's global account, which the app looks up per call
   - C. From the host name and the token, which must name the same tenant
   - D. From the database, which stores the last tenant that logged in

   Answer: C. The application router reads the subdomain with TENANT_HOST_PATTERN, and the login service issues a token naming the tenant. The lab refuses a request when the two differ (T08).

2. What must the onSubscription PUT callback return when Brennock subscribes?
   - A. A 201 status and the new database's connection string
   - B. A 200 status and the tenant's URL in the response body
   - C. A 202 status and a job ID that the provisioning service polls
   - D. A 200 status and the list of dependent reuse services

   Answer: B. SAP's documentation says the PUT callback returns 200 and the tenant's access URL. Dependencies come from the separate getDependencies callback.

3. In `--weak` mode, why does T08 pass while T07 fails?
   - A. Because the rate limit hides the leak from T08's single request
   - B. Because weak mode turns off the token check for the same tenant
   - C. Because Ostervale's tenant was already unsubscribed by then
   - D. Because the door check works, but the read skips the filter

   Answer: D. T08 tests the token against the host, which still works. T07 reads the shared table without WHERE tenant = ?, so Brennock gets Ostervale's rows. Isolation needs tests at the data layer too.

4. A new release adds a mandatory column. Ostervale's upgrade fails on its own data. What should the process do?
   - A. Roll the release back for every tenant until Ostervale is fixed
   - B. Report Ostervale, keep the others running, then retry it
   - C. Skip Ostervale and let the new code serve its old schema
   - D. Delete Ostervale's database and subscribe the tenant again

   Answer: B. With a database per tenant, one failure shouldn't stop the others. The lab reports the failed tenant, refuses to serve it on the old schema, and resumes once its data is fixed.

5. Why does CAP's recommended setup run `cds-mtx upgrade '*'` as a hook before the new app version starts?
   - A. Because tenants can't subscribe while an upgrade is running
   - B. Because the hook also creates the consumer subaccounts
   - C. Because new code should not serve tenants on the old schema
   - D. Because the sidecar can only start once in each deployment

   Answer: C. The new code expects the new schema. Upgrading the tenant databases first avoids errors like the "no such column" you saw in the CAP step for the tenant not yet upgraded.

6. Which tenant data is most often missed in a database-per-tenant design?
   - A. Rows in the tenant's own HDI container
   - B. The tenant's role collections in its subaccount
   - C. The tenant's subscription record in the registry
   - D. Shared caches, temporary files and log entries

   Answer: D. The database keeps tenants apart, but SAP warns that shared in-memory data is visible to all tenants. Caches, files, logs and jobs need the tenant in their key.

7. A utility in Germany wants the Fleet portal with its data in the EU. Calder's deployment is in `us10`. What do you tell them?
   - A. Subscribe from an EU subaccount; the data moves to the EU region
   - B. Subscribe from a US subaccount and ask SAP to copy the data
   - C. It needs a second deployment of the portal in an EU region
   - D. Subscribe normally; residency applies only to S/4HANA data

   Answer: C. SAP's guides require the consumer subaccount to be in the region where the app is deployed. EU residency means a separate EU deployment with its own tenants.

8. Using SAP HANA Cloud Tenant Management Service v2 with CAP, which plan does CAP insist on, and why?
   - A. `hdi-shared`, because it is the cheapest per container
   - B. `schema`, because schemas are easier to back up per tenant
   - C. `hana-multitenancy`, because other plans can expose other apps' data
   - D. `application`, because it matches the saas-registry plan name

   Answer: C. CAP's documentation warns that tenant containers are filtered by the SAP HANA Cloud service instance, so with another plan an app could reach other applications' data.

9. An agent in a multitenant app looks up pumps through a tool. Where should the tool get the tenant from?
   - A. From the user's question, which usually names the utility
   - B. From the agent's memory of the last tenant it served
   - C. From a tenant parameter that the model fills in per call
   - D. From the validated token, outside the model's reach

   Answer: D. Anything the model writes can be steered by a prompt injection. Taking the tenant from the validated token keeps the agent inside one tenant, just like the T08 check does for ordinary requests.

## Sources

- [Developing Multitenant Applications in the Cloud Foundry Environment (SAP BTP documentation, SAP-docs on GitHub, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/developing-multitenant-applications-in-the-cloud-foundry-environment-5e8a2b7.md): provider and consumer roles; each consumer has a dedicated subaccount in the provider's global account and subscribes by cockpit, btp CLI or REST API; dedicated URL per consumer; requests told apart by tenant ID; consumed resources billed to the provider; approuter, xsuaa and saas-registry with the application plan; six-step workflow
- [Develop the Multitenant Application (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/develop-the-multitenant-application-ff54047.md): shared in-memory data is visible to all tenants; no user code in the app process, no user file system access; PUT returns 200 and the tenant's URL; DELETE on unsubscribe; payload fields subscribedTenantId, subscribedSubdomain, globalAccountGUID, subscriptionAppName, subscribedLicenseType; first URL segment at most 63 characters; tenant-mode shared; Callback scope granted to $XSAPPNAME(application,sap-provisioning,tenant-onboarding)
- [Register the Multitenant Application to the SAP SaaS Provisioning Service (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/register-the-multitenant-application-to-the-sap-saas-provisioning-service-3971151.md): saas-registry instance with the application plan, one-time per app; getDependencies and onSubscription ending in /{tenantId}; appPlans visible only in the provider's global account, allowedTargetPlans; onSubscriptionAsync with callbackTimeoutMillis, after which the subscription is FAILED; allowContextUpdates
- [Configure the approuter Application (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/configure-the-approuter-application-5af9067.md): one application router per multitenant app; development URL subdomain-approuterhost.domain, production wildcard on a custom domain; TENANT_HOST_PATTERN; the login service finds the tenant's identity zone and identity provider and issues a JWT with tenant, user and scopes
- [Providing Multitenant Applications to Consumers in the Cloud Foundry Environment (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/providing-multitenant-applications-to-consumers-in-the-cloud-foundry-environment-7a013f1.md): the provider creates a subaccount per consumer in the same global account, subscribes each and sets up roles; consumers of a non-SAP provider typically don't own or access their subaccount; subscription management dashboard
- [Subscribe to Multitenant Applications Using the Cockpit (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/subscribe-to-multitenant-applications-using-the-cockpit-7a3e396.md): consumer subaccount in the region where the app is deployed; subaccount entitled to the app; plans of type subscription; deleting a subscription deletes the app's data for that subaccount; role collections or authorization policies afterwards
- [Using a Custom Domain for the Multitenant Application (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/using-a-custom-domain-for-the-multitenant-application-c52ca39.md): on the default domain a route per tenant is created by hand; a wildcard route on a custom domain avoids that; a separate route for the callbacks; changing the domain later means updating each subscription's URL in the dashboard; blue-green deployment recommended
- [Multitenancy Development Guideline (ABAP environment, SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/multitenancy-development-guideline-9d994c8.md): clients as tenants; isolation "isn't completely ensured" by the infrastructure; no system check of multitenancy compliance, external audit proposed where isolation is a legal requirement; client-dependent tables; system date in UTC for all tenants
- [Deploy Multitenant SaaS Applications (CAP documentation, cap-js/docs, last commit 2026-11-18)](https://cap.cloud.sap/docs/guides/multitenancy/): cds add multitenancy adds @sap/cds-mtxs and a sidecar; local test with cds watch mtx/sidecar, cds watch --with-mtx, cds subscribe and cds upgrade; a database per tenant; subscriber subaccount in the provider's region; cds-mtx upgrade '*' as a Cloud Foundry hook before start; SAP HANA TMS v2 with the hana-multitenancy plan only; SaaS dependencies; CAP Operator on Kyma and Gardener
- [MTX Services Reference (CAP documentation)](https://cap.cloud.sap/docs/guides/multitenancy/mtxs): SaasProvisioningService, DeploymentService, ModelProviderService, ExtensibilityService, JobsService; job settings workerSize, clusterSize, queueSize; technical tenant t0 holds operational metadata, not the domain model
