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.
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). 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.
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).
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).
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).
The ABAP environment. ABAP-based SaaS uses clients in one ABAP system as tenants, orchestrated by the ABAP Solution service (SAP BTP documentation).
The subscription management dashboard. A screen for the provider to see every subscription, its status and its errors (SAP BTP documentation).
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). 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.
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.
"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).
"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.
Pick one answer for each question. The explanation appears after you choose.
1Calder's distributors log in to an app to see the status of their own orders. Should it be multitenant?
Answer: C. 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.
2What is the strongest business reason to build an app as multitenant?
Answer: D. 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.
3Who pays for the BTP resources that a multitenant app uses for all its tenants?
Answer: C. 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.
4Calder wants one shift-handover app for Rockford and Augsburg, and Augsburg's data must stay in the EU. What fits?
Answer: C. 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.
5A vendor says its BTP platform guarantees that tenants can't see each other's data. What should a leader ask?
Answer: C. 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.
6A customer of Calder's Fleet portal leaves. What must be settled before its subscription is deleted?
Answer: B. 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.
7A new release of a multitenant app is deployed. What else has to happen?
Answer: D. 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.
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?
SAP's Cloud Foundry guide lists the parts of a multitenant app (SAP BTP documentation):
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
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
When a consumer subaccount subscribes, the SaaS Provisioning service calls the app (SAP BTP documentation):
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.
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.
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).
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
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.
The application router matches the host against TENANT_HOST_PATTERN, a regular expression whose first capturing group is the tenant's subdomain.
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.
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.
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). The ABAP environment uses clients of one ABAP system as tenants (SAP BTP documentation).
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). Caches, logs, background jobs, search indexes and files all need a tenant in their key.
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, MTX reference). 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.
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). 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.
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]
In VS Code, create a new file unit21/tenant_lab.py.
Paste the code below and save.
"""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())
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.
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
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.
Run python unit21/tenant_lab.py show to list the tenants still subscribed.
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.
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.
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, 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.
In the terminal, from your course folder:
cd unit21
cds init fleet-portal
cd fleet-portal
cds add nodejs
Create db/schema.cds:
namespace calder.fleet;
entity Pumps {
key serial : String(20);
model : String(10);
site : String(40);
status : String(10);
}
Create srv/fleet-service.cds:
using calder.fleet as f from '../db/schema';
service FleetService {
entity Pumps as projection on f.Pumps;
}
Create db/data/calder.fleet-Pumps.csv with these two lines (CAP loads it into every new tenant):
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"}'
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:
alice sees DEMO-0001 and RK2611-0041; erin sees only DEMO-0001. Same app, two databases.
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:
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.
Unsubscribe one tenant with cds unsubscribe t2 --from http://localhost:4005. Its file db-t2.sqlite is deleted, data and all.
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). 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).
CAP with MTX. For CAP itself as an architect sees it, see CAP in depth 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). 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).
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). 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).
Operations tools: subscriptions are created in the cockpit, with btp subscribe accounts/subaccount in the btp CLI (SAP BTP documentation), 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). For production, SAP recommends a custom domain with a wildcard route, so no route is created per tenant (SAP BTP documentation).
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). For ABAP SaaS sold to customers, SAP points to registering the solution in the SAP Store (SAP BTP documentation). The commercial terms for selling a multitenant app to other companies are partner terms; confirm them with SAP.
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. 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). 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.
How do you prove one tenant can't read another's data, and does that test run on every release?
What happens to the tenants whose upgrade fails, and who is told?
Where else is tenant data kept: caches, logs, files, search indexes, AI prompts?
What does onboarding cost per tenant, and which steps are still manual?
What do you give a customer when it leaves, and when is its data really gone?
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.
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 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.
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 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.
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.
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.
Open unit21/tenant_lab.py.
Add a fifth candidate to CANDIDATES, after MT04:
{"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"},
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.
Add Harwell's pump to PUMPS:
"harwell": [("RK2612-0051", "ES-200", "Well field pump house", "2027-12-10")],
In run(), just before the line passed = sum(results), add two checks:
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}")
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.
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.
Pick one answer for each question. The explanation appears after you choose.
1In the Fleet portal, where does the app learn which tenant a request belongs to?
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).
2What must the onSubscription PUT callback return when Brennock subscribes?
Answer: B. SAP's documentation says the PUT callback returns 200 and the tenant's access URL. Dependencies come from the separate getDependencies callback.
3In --weak mode, why does T08 pass while T07 fails?
Answer: A. 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.
4A new release adds a mandatory column. Ostervale's upgrade fails on its own data. What should the process do?
Answer: C. 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.
5Why does CAP's recommended setup run cds-mtx upgrade '*' as a hook before the new app version starts?
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.
6Which tenant data is most often missed in a database-per-tenant design?
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.
7A utility in Germany wants the Fleet portal with its data in the EU. Calder's deployment is in us10. What do you tell them?
Answer: B. 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.
8Using SAP HANA Cloud Tenant Management Service v2 with CAP, which plan does CAP insist on, and why?
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.
9An agent in a multitenant app looks up pumps through a tool. Where should the tool get the tenant from?
Answer: A. 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.
Develop the Multitenant Application (SAP BTP documentation)— 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)— 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)— 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
Subscribe to Multitenant Applications Using the Cockpit (SAP BTP documentation)— 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)— 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)— 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)— 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)— SaasProvisioningService, DeploymentService, ModelProviderService, ExtensibilityService, JobsService; job settings workerSize, clusterSize, queueSize; technical tenant t0 holds operational metadata, not the domain model