Tenant isolation and cost attribution
Make each data operation tenant-scoped
Tenant authorization checks whether the authenticated identity may perform an action for a tenant. Data-layer enforcement restricts which records can actually be read or changed. Both matter. If Cedar requests invoice 7, the query must use Cedar and 7, not only 7. A valid user identity does not imply membership in every tenant. A successful membership check is not sufficient if the data access layer ignores the tenant boundary.
For this exercise, use an in-memory SQLite database with composite primary keys and parameterized reads. Identity verification is represented by a trusted caller argument in the local test only; never use that shortcut in a network service. The model supports read-only access, known tenant membership, a role check and active tenant state. No cloud accounts, real data or credentials are needed.
Executable local example
Run with Python 3 and its standard-library SQLite module. The function checks membership and role independently of the SQL predicate. A denied request has the same response shape as a missing record; the restricted audit stream distinguishes outcomes. This is not a timing-side-channel defense, database row-level security implementation or production authentication mechanism.
import sqlite3
MEMBERS = {('alice', 'cedar'): 'reader', ('bob', 'maple'): 'reader', ('eve', 'cedar'): 'billing-only', ('alice', 'closed'): 'reader'}ACTIVE = {'cedar', 'maple'}
def make_db(): db = sqlite3.connect(':memory:') db.execute('CREATE TABLE invoices (tenant TEXT, id INTEGER, ' 'cents INTEGER, PRIMARY KEY (tenant, id))') db.executemany('INSERT INTO invoices VALUES (?, ?, ?)', [('cedar', 7, 1200), ('maple', 7, 900), ('maple', 8, 500), ('closed', 7, 300)]) return db
def read_invoice(db, audit, user, tenant, invoice_id): if (tenant not in ACTIVE or MEMBERS.get((user, tenant)) != 'reader' or type(invoice_id) is not int or invoice_id <= 0): audit.append((tenant, 'read', 'denied')) return None row = db.execute('SELECT cents FROM invoices ' 'WHERE tenant = ? AND id = ?', (tenant, invoice_id)).fetchone() audit.append((tenant, 'read', 'found' if row else 'missing')) return row[0] if row else None
db = make_db()audit = []for user, tenant, invoice in [('alice', 'cedar', 7), ('alice', 'maple', 7), ('alice', 'cedar', 8), ('bob', 'maple', 7)]: print(read_invoice(db, audit, user, tenant, invoice))print(audit)db.close()Expected output:
1200NoneNone900[('cedar', 'read', 'found'), ('maple', 'read', 'denied'), ('cedar', 'read', 'missing'), ('maple', 'read', 'found')]Alice receives Cedar's invoice 7, not Maple's similarly numbered record. She cannot read Maple's invoice or Cedar's nonexistent invoice 8. Bob receives Maple's 7. The local audit list is intentionally not exposed to tenants. It uses synthetic tenant labels, including an untrusted requested tenant on denials; production logs should identify verified actor and requested target separately, include request IDs and timestamps, validate/sanitize fields, and apply retention and access control. Never log invoice contents or credentials.
Test negative cases before claiming isolation
Run additional cases: Eve is a member of Cedar but lacks the reader role; Alice is a member of an inactive tenant; an unknown user has no membership; an invalid invoice identifier is rejected; Bob cannot read Cedar. Check exact returned values and audit outcomes. Check database rows remain unchanged. In a real system test every list, search, update, delete, export, batch, cache and background-job path, including stale credentials, membership revocation and support access. Database-native row policies (where supported), tenant-scoped roles and network controls provide additional independent protection. This local example only tests a single read path; it cannot establish complete tenant isolation.
Attribute shared costs with an explicit driver
Direct costs are attributable to a tenant, such as a dedicated database. Shared costs require a documented allocation driver that approximates consumption, such as request count, compute seconds or stored GB. Chargeback assigns costs to budgets; showback reports them without transferring charges. Neither equals SaaS invoice revenue or pricing tier entitlements.
Fictional monthly USD: shared API $300, shared support infrastructure $100, Cedar dedicated storage $40, Maple dedicated storage $80. Allocate the $300 API by measured requests (Cedar 3 million, Maple 1 million), and the $100 common infrastructure equally. Cedar receives 225 + 50 + 40 = $315; Maple receives 75 + 50 + 80 = $205. Total = $520, matching the ledger. Cost per million requests is $105 for Cedar and $205 for Maple with this model. Different drivers may produce different results; a small tenant can carry more cost per request. Zero total usage means the usage-based share cannot be computed; record the cost as unallocated or apply a separately approved fixed driver. Do not silently drop it. Round monetary allocations consistently and reconcile any remainder to a documented owner.
Separate currencies and billing periods. Keep cost allocation and customer invoices separate. Include migration overlap, dedicated idle capacity, backups and logging when in scope. Use Azure cost allocation guidance and Google BigQuery multi-tenant guidance as service-specific starting points, not universal billing rules.
Practice: isolate, measure, reconcile
Extend the scenario with a third tenant, Birch, without modifying existing tenants' rows. Describe how to add the membership and tenant state, write one positive and three negative tests, and prove that the shared cache and queued jobs include ownership checks. Recompute the API allocation for request weights 3:1:0, keep the direct costs distinct, and explain why a zero-usage tenant could still incur a fixed allocation. State what evidence would be required before shipping: integration tests across all tenant-facing operations, policy review, capacity tests, audited logs, restore rehearsal and independent security review. Continue to specialized cloud workloads for service-specific capacity and isolation decisions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tenant isolation and cost attribution — knowledge check
Choose the best answer for each offline scenario.
Which SQL predicate scopes invoice 7 to Cedar?
Eve is a Cedar member but has no reader role. What is expected?
Allocate $300 by request weights 3:1. What is Maple’s share?
If total metered usage is zero, what should happen to the shared cost?
What does passing the SQLite read tests establish?