Ch.76: SaaS System Design: Stop One Customer Taking Over
Outline
- 0:00 One app, two companies
- 0:41 The request path and the work it leaves behind
- 1:19 What a customer can do
- 1:58 Define the constraints before buying isolation
- 2:55 A company selector is a request, not proof
- 4:01 Two invoice numbers, two database scopes
- 6:16 The cache can leak before the database answers
- 7:24 The request ends, the company boundary continues
- 8:39 One request can consume the whole shared pool
- 9:54 Bound running work as well as waiting work
- 11:53 A dedicated database isolates one resource
- 13:16 Trace each boundary, then test the shared resource
Transcript
0:00 Cedar and Harbor use the same hosted invoice app. That's a multi-tenant SaaS service: one application serving separate customer companies. Each company is a tenant, and its users expect their invoices to stay theirs. We'll design its backend for requests and imports, keeping company data separate and shared work bounded. Both companies have invoice 42. When Maya from Cedar opens it, whose document comes back? Only Cedar's. The invoice number can be right and the company wrong. Without tenant scope, our shared app can hand Maya Harbor's confidential document.
0:31 And Cedar's large import must leave processing capacity for Harbor too. Data separation and resource fairness are different tests; a successful login solves neither. On this complete map, the upper path handles someone's request. Entry checks the user and chosen company, then carries that company through the invoice service to its data. Where does Maya's import go after the response? The lower path is work continuing after the response: saved import jobs, queues and background processes called workers.
1:01 Their results still belong to one company. So Maya can have her response while Harbor still has to compete with her import. Those side controls decide where Cedar runs and how much work it can start. We'll trace her operation through both paths, then return here to check Harbor. With both paths mapped, let's pin down the functional requirements: Maya needs to read or update her company's invoices, start an import and check its progress. Eli belongs to both firms. He selects Cedar to read an invoice, then Harbor.
1:33 Harbor accepts his read but refuses his import. Ah, his read can pass while his import fails. So those need separate checks. We also register each company and know where its data lives. Does that location record give each company its own deployment? Not necessarily. Microsoft's architecture guidance separates the customer company from the deployment. We choose what to share after setting the data and capacity requirements. Our non-functional requirements start with a hard data boundary: no Harbor records in an ordinary Cedar operation, even when invoice numbers collide.
2:06 And missing trusted company context must stop access. I'd rather reject that request than fill in a default company. For fictional demand, take 1,000 companies averaging 10 interactive requests a second: 10,000 overall. Maya's import adds just one to that request total, then leaves the workers with the rest of the bill. How would you check Harbor's experience while that runs? Load-test whether 95% of regional interactive requests finish within 200 milliseconds, including realistic import demand.
2:34 That's an unmeasured target. Imports may wait when capacity is full; we mustn't hide that waiting behind an instant completion message. Nor can we promise zero interference while sharing infrastructure. A database outage may still affect both companies. We need to say which risk each choice reduces. Now let's follow Maya's request. Now Maya sends an authenticated request naming Harbor. Our example membership store says she belongs only to Cedar. What should happen before reading an invoice? Reject that selection before reading invoice data.
3:07 A path or header can say which company she wants, but it doesn't prove she belongs there. My first thought was to put the company identifier in every request and consider that finished. I'd preserved a label without establishing who could use it. Yeah. The server validates Maya's identity, her membership and the allowed operation. It constructs that internal context only after accepting Cedar as her selected company. The context carries Cedar, Maya and the operation. A directory maps Cedar to its deployment.
3:36 Routing chooses the destination; it doesn't replace the permission check. And internal services accept that context through our trusted service path. They can't take a fresh client header and quietly switch the operation to Harbor. That's our trust boundary: clients cannot call storage directly, forge server job records or run arbitrary database queries. A compromised application needs additional defenses beyond this exercise. With Cedar's request validated, follow the two rows on screen. Invoice identity is company plus invoice number.
4:07 Cedar's 42 and Harbor's 42 are different records. Then Cedar's invoice must link to Cedar's customer seven, not Harbor's customer seven. The same company key belongs in indexes and uniqueness rules too. Suppose a new endpoint forgets its company condition. We can add database row-level security, a policy that limits which rows an application role can access. So the database checks the row's company against trusted request context even when the ordinary query missed that filter? Yes, under the policy and role assumptions on screen.
4:39 PostgreSQL's documentation also names the bypasses. Superusers and special bypass roles aren't constrained by these policies. Hold on, which database role should we use so the policy actually constrains the service instead of being bypassed during the test? A non-owner role without bypass powers. Owners normally bypass policies too, so normal service reads use the constrained account. Our trusted application still establishes the company context. It guards a missing row condition, while invented application context can still select the wrong company.
5:11 Exactly. Now take a connection whose session-wide setting says Cedar. Harbor establishes a local context, reads Harbor and commits. What remains underneath? I'm not sure whether that old session value survives commit. I was expecting an empty setting. It does. The local value ends; PostgreSQL restores the session setting underneath. A later operation without initialization can now read Cedar. Transaction-local context alone didn't clean the connection. Oh, ending the transaction wasn't cleaning the connection.
5:40 Our pool contract must establish an empty company baseline before handing it out again, and verify it. Harbor's transaction can then set its validated company locally. Yes. Harbor's query reads Harbor. Commit or rollback returns this connection to that empty baseline, as the new timeline shows. What if we deliberately skip the next company initializer? No rows. Our visible policy needs a row matching a nonempty company setting. This empty setting matches neither company. And test with the actual service role and connection pool.
6:11 A policy demonstration run as an administrator could bypass precisely what we're trying to verify. Before relying on that row policy, look at the cache entry. Cedar's invoice sits under the key invoice 42. Harbor now asks for its 42. Wait, if that cache hit returns Cedar's invoice before the database runs, where could our row policy stop it? It can't. Construct the key from the validated tenant and invoice identity, as the separate entries show. Keep cached versions for different access rights separate too; a cache doesn't get to widen access.
6:44 Oh, I'd make that collision deliberate in the test: give both companies matching invoice numbers, fill one cache entry, then request the other. Globally unique test IDs might conceal the bug. I'd reuse your deliberate collision for the join test too. Both companies have customer seven on screen. Matching on company as well as customer number prevents the crossed relationship. Result files need the same treatment. A company-prefixed object path keeps names apart, but the download still needs an access decision.
7:14 So namespacing preserves which resource we mean. It isn't a grant to whoever guesses its path. That's the distinction to carry into background work. Now carry that scope into Maya's authorized import. The server saves job 91 with Cedar and the selected source, then queues its job identifier. I could send the selected company and source file straight on each message and save the worker a lookup. What do we gain from the server job record? One durable, trusted binding for the accepted job. A changed message can't turn 91 into Harbor's import.
7:50 The queue tells us which job to load; it doesn't get to redefine who owns it. Ah, and time has passed since Maya clicked import. The worker loads that record, checks Cedar is still enabled and establishes fresh job-scoped data context before reading the file. Then each bounded chunk uses the same scoped data path. Progress and result objects refer back to that job and its company. And after a Cedar chunk, a Harbor job may use that worker process. No leftover global company variable or database session should follow it.
8:22 Right. Retried work still names the original job and chunk, so it can't quietly change customer ownership. Avoiding duplicate effects needs separate write-retry rules, outside this design. Even with every record belonging to Cedar, that same import can still exhaust our shared workers. Then consider that import creating 1,000 chunks. A small invoice read and that import were each one incoming request. Equal request counts didn't mean equal work. So an entry-point request limit can pass while the queue, workers or database become saturated.
8:55 We need to find which shared resource is actually busy. Amazon's published 2020 builder account gives a concrete example: a nightly fleet audit loaded a shared database and slowed a separate deployment tool. The audit could tolerate being slow; the tool's users couldn't. One database utilization number doesn't tell us whose experience we're protecting. Right. In our visible trace, eight Cedar chunks already occupy eight workers. Harbor has a separate queue and one small job. Will separate queues start it?
9:26 No. Harbor has its own queue and nowhere to run. A new queue can't interrupt those running chunks or create processing capacity. Exactly. Adding more web servers wouldn't free them either. We'd measure per-company running work, queue age, database load and the overall limits before scaling the wrong component. That's the noisy-neighbor problem: one customer's work slows another. The data can be perfectly separated while the service still becomes unusable for Harbor. With those eight workers occupied, we can't impose a cap and expect Harbor to start.
9:59 Consider a fresh run with Cedar capped at four before dispatch, in the same eight-slot pool. The picture now gives Cedar four slots and Harbor one, with three free. Cedar's remaining work waits instead of occupying every process. Yes. Pick among eligible tenant queues rather than draining one company's entire backlog first. Also bound queued work so acceptance doesn't become unlimited storage for imports. With only Cedar active, its admin sees four idle workers: 'Are we leaving my import waiting so other companies can get a turn?'
10:30 We are in this simple exercise. Lending unused capacity is possible, but you need bounded chunks and a way to restore other tenants' access when they arrive. Right, because lending eight uninterruptible jobs recreates our original delay. A setting called fair wouldn't help Harbor while those jobs continue. Nor do four worker slots bound every resource. One chunk may launch several database queries. Look at the next query from an already-running Cedar worker. That worker has a slot. Why should its next query have to wait?
11:00 Take a separate miniature database example: one running query per company and two in total. Our shared query-admission component issues a permit only when there's room in both allowances. Cedar's first query runs; its next waits. Could that waiting query take the other total permit before Harbor asks? No. Admission reserves both allowances in one indivisible decision before the query starts. Cedar's waiting query holds neither, so Harbor can start. With the total full, other companies wait too. A finished query releases its permit.
11:31 The lookup and sort on screen each use one permit. The sort can still demand more memory and storage work. Counting queries isn't measuring their cost. These counts don't size production. Neither miniature trace proves our interactive latency target. We need resource bounds and realistic full-demand load tests. Stronger customer separation means deciding which resources to stop sharing. With per-company work bounded, suppose a large customer needs more separation. The comparison offers shared tables, a dedicated database or an entire dedicated deployment.
12:02 Which boundary changes? Shared tables rely on scoped access and policies. A separate database gives that customer a separate data boundary. It doesn't tell us which processing or storage capacity is dedicated; we'd have to specify that too. Ah, then the database label alone doesn't settle the capacity question. Even with separate database capacity, eight busy shared workers would still leave Harbor waiting. Correct. A dedicated complete deployment separates more of those resources, while adding capacity and operational overhead for that customer.
12:33 Consider Maya naming Harbor's dedicated deployment. Does that change whether we let her in? No, her membership is Cedar-only. Reject her Harbor selection before routing. For Eli's accepted Harbor read, look up Harbor in the directory: it returns the dedicated deployment. Our shared control plane keeps those placements and customer settings current as companies join or choose a different setup. Those shared management services can still affect many customers. We should name that remaining dependency rather than drawing isolation as a perfect wall. Exactly. Choose separation from the customer's requirements and the resource measurements. A migration between deployments would need its own safe design; changing the directory isn't that migration.
13:12 Yes. Let's trace those boundaries on the original map. With those boundaries chosen, Maya's accepted Cedar request checks its company-scoped cache. A cache miss needs a query permit and scoped row access. The queue points to her saved Cedar job. Each worker establishes Cedar's context, and its result needs Cedar's access check. Alongside it, Harbor gets Harbor's invoice and can dispatch work without Cedar occupying the whole background pool under our exercise limit. We still measure the database and total load. Shared resources retain interference and outage risk, and our latency goal needs an actual load test. Consider a Harbor read on our clean connection.
13:52 Its baseline is empty, but we skip the next initializer. Which invoice comes back? No invoice. Our service role sees no row matching the empty company setting. If a company row appears, check the connection reset and caller role. Then reuse the worker and test colliding cache and job identities. We'd still test Harbor's experience during Cedar's import and ask which dedicated resources remove that pressure. The public source links are in the description. Thanks for listening to Learning Podcasts.