One codebase, many schools: keeping their data apart
An online learning platform sold to several schools and universities has a problem that single-customer products do not have: one application must serve different organizations without the data of one ever ending up in front of another. This is called multi-tenancy, and the tenant is the customer organization, with its users, its courses and its rules. The short answer is that you have three ways to keep the data apart (one database per tenant, one schema per tenant, shared tables with a tenant_id column) and that the choice rests on three questions: how much isolation your contracts demand, how many schema migrations you can run at every release, and how heavy your largest tenant is.
This is the first article in the series on engineering for EdTech. It assumes you know SQL, the HTTP request-response model and the idea of a signed token (JWT). No Kubernetes or Kafka skills are needed: where they appear, we explain them just enough.
One concrete example runs through the whole text. Imagine two customers, a university and a technical institute, using the same platform. A university student opening the course list must see the university's courses and nothing else, even if the developer who wrote that query forgot a WHERE. Every choice that follows answers that case: what prevents the data leak when the human error is there?
The three isolation models and what they cost
With one database per tenant each customer has a database of its own. The isolation is physical: a query error cannot cross the boundary because the boundary is the connection. You pay the price elsewhere: every schema migration must run on all the databases, and every database consumes connections, space and backups even if the customer has ten users. It is the model that makes sense when customers are few, large and bound by contracts that ask for physical separation or independent restore.
With one schema per tenant (in PostgreSQL a schema is a namespace inside the same database) customers share the server but not the tables. Isolation is strong and the cost per customer is lower, but migrations remain N: the script that adds a column must iterate over all the schemas, and a failure halfway leaves customers with different versions of the structure. The boundary that protects you is the schema name in the connection's search_path.
With shared tables and tenant_id all customers live in the same tables, and each row says who it belongs to. A migration runs once and a new customer costs one row in tenants. In exchange, isolation is no longer a structure but a rule: if a query forgets the filter, the data get mixed. This is where row-level security comes in, which we will see shortly, to move the rule from the application code to the database.
| Question | Database per tenant | Schema per tenant | Shared tables + tenant_id |
|---|---|---|---|
| What keeps the data apart | The database | The schema | A rule on the rows |
| Migrating one column | One per database | One per schema | Just one |
| Restoring a single customer | You restore its database | You restore its schema | You must extract its rows |
| A very large customer slows the others down | No, if the databases sit on different machines | Yes, server and disk are shared | Yes, tables and indexes are shared too |
| If the developer forgets the filter | It cannot happen | It cannot happen, if the search_path is right | Data leak, unless RLS is in place |
The table does not name a winner, and it should not: it shows that every row where one model is strong is a row where another is weak. The first two rows measure the work you do (migrations and restores), the last two the risk you run when something goes wrong. In the guidance Microsoft publishes on multitenant architecture (you will find it in the sources) the risk of the loud customer, the noisy neighbor, is treated as a separate selection criterion: a customer with an exam peak can consume the resources the others expect to have.
Resolve the tenant before anything else
Whichever model you choose, the first operation of every request is to answer one question: which customer is this call from? This step is called tenant resolution and it is the security boundary of the whole system: if it gets it wrong, everything that follows works on the wrong customer. There are four possible sources for the answer.
- Subdomain (
university.lms-platform.com): the most common, and it requires a wildcard DNS record and a certificate that covers it. - Path prefix (
/t/university/courses): it needs no DNS, but it pollutes every address of the API. - HTTP header (
X-Tenant-ID): handy for machine-to-machine calls, but it is chosen by the caller. - Claim in the token: the tenant is written into the JWT at login time, and to change it you log in again.
The list has a hidden order of trust, and it is the thing to take home. The subdomain and the token claim are controlled by whoever runs the platform (the DNS and the signature); the path and the header are written by whoever calls. That is why a single source is not enough: the request says which tenant it wants to access (subdomain), the token says which tenant the user belongs to, and the two must match. If they do not match, the correct answer is 403, not an attempt to guess.
The listing below implements this logic as a pure function, without depending on Express: it receives the host name, the optional header and a repository, and returns either the tenant or an error with the HTTP code to use. Keeping the framework out is deliberate, because that way the rule can be tested in a few seconds without starting a server, and the link to Express shrinks to three lines of adapter. The subdomain takes precedence (extractSubdomain(host) ?? headerSlug), reserved names such as www and api do not count as tenants, and a deactivated tenant answers 404 like a nonexistent one, so as not to reveal which customers exist.
export interface TenantConfig {
readonly id: string;
readonly slug: string;
readonly isActive: boolean;
}
export interface TenantRepository {
findBySlug(slug: string): Promise<TenantConfig | null>;
}
const RESERVED = new Set(['www', 'api', 'admin', 'status']);
export function extractSubdomain(host: string): string | null {
const parts = host.split('.');
if (parts.length < 3) return null;
return RESERVED.has(parts[0]) ? null : parts[0];
}
export type Resolution =
| { readonly ok: true; readonly tenant: TenantConfig }
| { readonly ok: false; readonly status: 400 | 404; readonly error: string };
// Pure function: no Express Request/Response, so it can be tested without a server.
export async function resolveTenant(
host: string,
headerSlug: string | undefined,
repo: TenantRepository,
): Promise<Resolution> {
const slug = extractSubdomain(host) ?? headerSlug ?? null;
if (!slug) return { ok: false, status: 400, error: 'TENANT_NOT_RESOLVED' };
const tenant = await repo.findBySlug(slug);
if (!tenant || !tenant.isActive) {
return { ok: false, status: 404, error: 'TENANT_NOT_FOUND' };
}
return { ok: true, tenant };
}
// The token carries the tenant the user logged in with: it must match the one of the request.
export function tenantMatches(tokenTenantId: string, resolved: TenantConfig): boolean {
return tokenTenantId === resolved.id;
}
// ---- test ----
const db: Record<string, TenantConfig> = {
mit: { id: 't-1', slug: 'mit', isActive: true },
unibo: { id: 't-2', slug: 'unibo', isActive: true },
legacy: { id: 't-3', slug: 'legacy', isActive: false },
};
const repo: TenantRepository = { findBySlug: async (s) => db[s] ?? null };
const cases: Array<[string, string | undefined]> = [
['mit.lms-platform.com', undefined],
['api.lms-platform.com', 'unibo'],
['api.lms-platform.com', undefined],
['legacy.lms-platform.com', undefined],
['mit.lms-platform.com', 'unibo'],
['localhost', undefined],
];
for (const [host, header] of cases) {
const r = await resolveTenant(host, header, repo);
console.log(host.padEnd(26), String(header).padEnd(10), r.ok ? `ok ${r.tenant.slug}` : `${r.status} ${r.error}`);
}
const r = await resolveTenant('mit.lms-platform.com', undefined, repo);
if (r.ok) console.log('token of t-2 on mit:', tenantMatches('t-2', r.tenant));
// Output:
// mit.lms-platform.com undefined ok mit
// api.lms-platform.com unibo ok unibo
// api.lms-platform.com undefined 400 TENANT_NOT_RESOLVED
// legacy.lms-platform.com undefined 404 TENANT_NOT_FOUND
// mit.lms-platform.com unibo ok mit
// localhost undefined 400 TENANT_NOT_RESOLVED
// token of t-2 on mit: false
The listing was run with Node 24, which runs TypeScript files by stripping the types. The output shows the cases that matter. The row with api.lms-platform.com and unibo resolves through the header because the subdomain is reserved; without the header it answers 400. The row mit.lms-platform.com with header unibo resolves mit and ignores the header: the subdomain wins, and that is what you want, because otherwise whoever controls the header would choose the tenant. The last row shows the tenantMatches function: a token issued for t-2 is not valid on mit. The link to Express (reading req.hostname, answering with res.status) was not run here: it is a pattern to adapt.
Row-level security: moving the rule into the database
In the shared-tables model the risk is the query without a filter. PostgreSQL's row-level security (RLS) takes the responsibility away from the application code: you declare a policy on the table and the database adds the condition by itself to every SELECT, UPDATE and DELETE. The listing shows a courses table, with a primary key that starts with tenant_id (so every per-customer search uses the index) and a policy that compares the column with a session parameter.
CREATE TABLE tenants (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
slug varchar(63) UNIQUE NOT NULL,
is_active boolean NOT NULL DEFAULT true
);
CREATE TABLE courses (
id uuid NOT NULL DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES tenants(id),
slug varchar(255) NOT NULL,
title varchar(500) NOT NULL,
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, slug)
);
ALTER TABLE courses ENABLE ROW LEVEL SECURITY;
ALTER TABLE courses FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON courses
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);
-- For every request, inside the transaction:
BEGIN;
SELECT set_config('app.current_tenant_id', '6f1c0a52-8d1e-4c7b-9a43-2b7e5d0c1f10', true);
SELECT title FROM courses; -- sees only the courses of that tenant
COMMIT;
This block was not run: it needs a PostgreSQL server, and none was started for this check. Every statement that follows rests on the official documentation on row security policies. The most treacherous point is FORCE ROW LEVEL SECURITY: the documentation says that superusers, roles with the BYPASSRLS attribute and normally the table owner as well skip RLS. If the application connects with the role that created the tables, the policy does nothing; that is why you need an application role different from the owner, and FORCE as a second belt. The parameter is set with set_config(..., true): the third argument true makes it valid only for the current transaction, and it is essential when connections are shared across requests, because a value left over from the previous request would show the wrong customer's data.
Two details complete the picture. The first: current_setting('...', true) with the second argument set to true returns NULL instead of raising an error when the parameter is not defined (the documentation of the administration functions says so); wrapped in NULLIF(..., '') it also covers the empty-string case, and a comparison with NULL is never true, so a request without a tenant sees no rows instead of all of them. The second: the documentation warns that referential integrity checks (primary keys, UNIQUE, foreign keys) ignore RLS, so a customer can infer the existence of someone else's row from a duplicate error. That is why the public addresses of objects (the slugs) are unique per tenant and not globally.
Authentication, roles and APIs without the tenant in the path
The signed token solves two problems at once: it proves who the user is and it carries the tenant they logged in with. Whoever verifies the token must also check the audience or the tenant claim against the one resolved from the address, which is the tenantMatches function of the previous listing. As for roles, a four-level scheme almost always covers the need: student (their own courses), teacher (the courses they teach), tenant administrator (the whole customer) and platform operator (all customers, with a separate role and audit log, never the same account as an administrator).
Since the tenant comes from the address and the token, the APIs do not repeat it in the path: GET /api/v1/courses returns the current customer's courses, and the same path serves everyone. The advantage is not only aesthetic. A path such as /tenants/42/courses invites the client to change the number and forces the server to check every time that 42 matches the one in the token, whereas without the parameter that error cannot even be expressed. With GraphQL the same applies: the tenant context lives in the resolver context, never in an argument.
Files and video: isolation is repeated in storage
Heavy content (PDFs, slides, video, student submissions) does not live in the database but in an object store, and the isolation must be repeated there. The simplest approach is a single container with the tenant as the first path segment ({tenant_id}/courses/{course}/lesson-01.mp4) and an access policy tied to that prefix. File addresses must not be published: they are signed with a short expiry, so a forwarded link stops working. For video the pipeline is always the same (direct upload, transcoding into several resolutions, delivery from a CDN with signed links) and deserves an article of its own: you will find it in Video Streaming for Education.
Events: letting the rest of the system know something happened
When a student completes a lesson, different things must happen: update the progress percentage, perhaps unlock a badge, record the datum for the statistics. If the progress service called the other three in sequence, a failure in any of them would slow down or break the answer to the student. The alternative is to publish an event (a fact that has already happened and is immutable, such as lesson.completed) and let whoever is interested read it on their own. The badge is the subject of Gamification Engine, the statistics of Learning Analytics with xAPI and Kafka.
In a multi-tenant system the event always carries the tenantId, and it is also the partition key. According to the introduction to Apache Kafka, events with the same key end up in the same partition, and the consumers of a partition read them in the order in which they were written: you therefore get ordering per customer, which is what you need, without paying for it for everyone. The flip side is the hot partition. The listing uses a deterministic stand-in for Kafka (an FNV-1a hash function, not the real murmur2: real partitions will differ) and one tenant that produces twenty times the events of the others.
interface LmsEvent {
readonly eventId: string;
readonly eventType: string;
readonly tenantId: string;
readonly version: number;
}
// 32-bit FNV-1a: a deterministic stand-in. Kafka uses murmur2, so real
// partitions will differ; all that matters here is same key = same partition.
function partitionFor(key: string, partitions: number): number {
let h = 0x811c9dc5;
for (const ch of key) {
h ^= ch.charCodeAt(0);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h % partitions;
}
const P = 4;
const log: LmsEvent[][] = Array.from({ length: P }, () => []);
function publish(e: LmsEvent): void {
log[partitionFor(e.tenantId, P)].push(e); // the key is the tenant, not the event
}
const tenants = ['mit', 'unibo', 'polimi', 'sapienza', 'unito'];
let n = 0;
// one large tenant (mit) generates 20 times as many events as the others
for (let round = 0; round < 10; round++) {
for (const t of tenants) {
const copies = t === 'mit' ? 20 : 1;
for (let i = 0; i < copies; i++) {
publish({ eventId: `e${n++}`, eventType: 'lesson.completed', tenantId: t, version: 1 });
}
}
}
log.forEach((p, i) => {
const per = new Map<string, number>();
for (const e of p) per.set(e.tenantId, (per.get(e.tenantId) ?? 0) + 1);
console.log(`partition ${i}: ${String(p.length).padStart(3)} events`, JSON.stringify([...per]));
});
// Output:
// partition 0: 20 events [["sapienza",10],["unito",10]]
// partition 1: 210 events [["mit",200],["polimi",10]]
// partition 2: 10 events [["unibo",10]]
// partition 3: 0 events []
The output is the reason the listing exists. The events of mit (200 out of 240) all end up in partition 1, which receives 210 while partition 3 stays empty: ordering per customer is guaranteed, but the load is not. With a different key (for example tenant and course) you would distribute better, at the price of losing ordering between different courses of the same customer. There is no absolute right answer: if ordering per course is enough for your domain, the composite key is better. The numbers here are those of a simulation, not of a benchmark on Kafka.
Scaling: cache, distributed database and the limit of numbers
A learning platform has predictable peaks: the start of the semester, exam sessions. Before distributing the database it pays to put a cache where repeated reading is the rule: the tenant configuration (it rarely changes and you ask for it on every request), the list of published courses, the computed permissions. Every cache has a key, however, and the key must contain the tenant: a cache with the key courses:list mixes customers as efficiently as a database without a filter. The cache duration is a product choice, not a datum: it depends on how long a teacher accepts seeing a change that is not yet visible to students.
When a single database is not enough, the next step for the shared-tables model is Citus, a PostgreSQL extension that distributes tables across several nodes. The Citus documentation on the multi-tenant data model recommends exactly the structure we have built: distribute the tables by a common tenant_id column and turn the small tables shared between customers, such as tenants, into reference tables (copied to every node).
-- Each customer's tables are distributed by the same column
SELECT create_distributed_table('courses', 'tenant_id');
SELECT create_distributed_table('enrollments', 'tenant_id');
-- The small, shared table is copied to every node
SELECT create_reference_table('tenants');
-- Join with tenant_id in the condition and in the filter: it stays on a single node
SELECT c.title, count(e.id) AS enrolled
FROM courses c
JOIN enrollments e ON e.tenant_id = c.tenant_id AND e.course_id = c.id
WHERE c.tenant_id = '6f1c0a52-8d1e-4c7b-9a43-2b7e5d0c1f10'
GROUP BY c.title
ORDER BY enrolled DESC;
This block was not run either, because it requires a Citus cluster. Its point lies in the JOIN condition: the join happens on tenant_id as well as on id, and the WHERE restricts to a single tenant. Citus can thus send the whole query to a single node, where all the rows of that customer sit together (co-location); without the filter, or with a join that does not include the distribution column, the query has to cross the nodes and the advantage vanishes. A warning about numbers: in this article you will find no response times or per-node capacities, because without a cluster and a real load they would be invented. Measure them on your load, with your schema.
What Canvas teaches, and how to choose
A platform whose code you can read is Canvas LMS, published on GitHub by its publisher, Instructure. Its Gemfile declares the dependency on switchman (Gemfile.d/app.rb), and Switchman describes itself as an ActiveRecord extension for database sharding, with on-the-fly shard creation and cross-shard references (repository README). The useful lesson is not "use this product" but that per-customer sharding is a solution a monolithic application already in production can adopt without rewriting itself into separate services. I do not describe other platforms (Moodle, Open edX, the commercial services): without primary sources on their internal architectures, every claim would be a guess.
The choice among the three models, then, starts from constraints and not from preferences. If a contract requires you to be able to hand over or delete a customer's data in isolation, start from the database per tenant and accept the operational cost. If you have many small customers and a small team, shared tables with RLS are almost always the cheapest road to get working, provided you have seen three defenses in action together: a non-owner application role, FORCE, and tests that try to read another customer's data. The schema per tenant sits in the middle, but it forces you to treat migrations as a process with state (which schema is at which version?). On the services side, start from a monolith organized in modules and split out a service only when a specific load, such as video or statistics, asks for it: the next article, on path personalization, is a good candidate for a service of its own.
What you can do now
You can compare the three isolation models on four concrete criteria (migrations, restore, noisy customer, human error) and justify the choice in front of a customer. You can write a tenant resolution that does not trust the header and that checks the token against the address. You can configure an RLS policy avoiding the table-owner trap, and you know why the cache key and the event key must contain the tenant. The same principle, the per-customer boundary decided by the system and not by the goodwill of the code, returns in the filter of a tutor based on course notes (Personalized Tutoring with LLMs and RAG) and in the pseudonymization of remote exams (AI Proctoring Systems). The next step in the series is Adaptive Learning Algorithms; for versioned teaching content, Multi-Tenant Content Management.
Frequently asked questions
What is the best multi-tenant model for an LMS?
It depends on the constraints. Few large customers with contractual requirements for physical separation: one database per tenant. Many small customers and a small team: shared tables with tenant_id and row-level security, provided you use an application role that is not the owner of the tables.
Is row-level security enough to protect customers' data?
No, not by itself. Superusers, roles with BYPASSRLS and, as a rule, the table owner bypass it, and referential integrity checks ignore it. You need a dedicated application role, FORCE ROW LEVEL SECURITY where appropriate, and tests that try to read another tenant's data.
Where does the tenant go: in the path, in the header or in the token?
The requested tenant comes from the subdomain, the user's from the token, and the two must match. The header is chosen by the caller and should be used only between trusted services. In the path it invites tampering and forces one more check on every request.
Sources
- PostgreSQL: 5.9 Row Security Policies - who bypasses RLS (superusers, BYPASSRLS, the owner unless FORCE), the implicit WITH CHECK, the integrity checks that ignore it, accessed on 2026-11-12
- PostgreSQL: System Administration Functions - the behavior of
current_settingwithmissing_okand ofset_configwithis_local, accessed on 2026-11-12 - Citus: Choosing Distribution Column / multi-tenant data model - distribution by
tenant_id, reference tables, join co-location, accessed on 2026-11-12 - Microsoft Azure Architecture Center: Approaches to storage and data in multitenant solutions - RLS as isolation in a shared database and the noisy neighbor risk as a selection criterion, accessed on 2026-11-12
- Apache Kafka: Introduction - events with the same key in the same partition and read ordering per partition, accessed on 2026-11-12
- instructure/switchman (GitHub) - the project's official description as an ActiveRecord extension for sharding, accessed on 2026-11-12
- instructure/canvas-lms: Gemfile.d/app.rb - the line
gem "switchman", that is Canvas's dependency on Switchman, accessed on 2026-11-12
The two TypeScript listings were run with Node 24 (node resolver.ts, node events.ts) and the outputs shown are the real ones; the output of the second depends on the hash function chosen and says nothing about the partitions of a real Kafka. The two SQL blocks are patterns to adapt and were not run. No response time or cost is reported, because none was measured.
Commenti
Caricamento commenti...
Sign in to comment