Build a Tenant-Isolated Platform for Selling and Streaming Courses
System DesignModel answerLast updated
Design a SaaS learning platform where organizations run separate course catalogs, learners buy access via an external payment provider, and prerequisite rules gate enrollment.
Design a Multi-Organization Learning Marketplace
You are building a hosted learning platform. Many independent organizations (the tenants) each publish their own courses. Learners belong to one organization and can buy access to its courses. Payment is handled by an external gateway, but your system is responsible for recording what happened to every payment and for granting access correctly.
What the platform must do
- Tenant separation. Each learner belongs to an organization. Each organization controls its own catalog. A learner must not see another organization's courses unless that access has been explicitly authorized.
- Buying. Learners purchase courses. The payment itself happens at a third-party gateway, yet your system must track the status of each transaction.
- Instant access. After a successful purchase the learner should be able to open the course materials (videos, quizzes) right away.
- Prerequisites. Some courses can only be bought or enrolled in after other courses have been completed.
Quality requirements
- Scale: Browsing and video playback produce very heavy read traffic. The system should serve millions of users.
- Consistency: Purchase records must be correct, and enrollment state must match the real outcome of the payment.
- Security: Content may only be delivered to people who paid for it, and the check must be made in the context of the learner's own tenant.
What to cover in your answer
- Data model: the schema for tenants, users, courses, orders/purchases and their statuses.
- API design: the main endpoints for browsing, buying, and checking enrollment.
- Scale versus isolation: how you keep tenant data separate while still getting fast reads through caching and a CDN.
- Prerequisite enforcement: where and how the rule is checked in the purchase flow.
State your assumptions about traffic and tenant sizes, and explain the trade-offs behind your main choices.
Hints
Hint 1
Start by estimating load: reads dwarf purchases, and video bandwidth only works through a CDN. Use that to decide where you need strong consistency (orders, entitlements) and where eventual consistency is fine (catalog pages).
Hint 2
Never take the tenant from a request parameter; derive it from the authenticated token or hostname, put it first in every key and primary key, and consider a second layer such as row-level security and tenant-prefixed cache keys and storage paths.
Hint 3
Payment callbacks can be duplicated or arrive late. Think about an idempotency key on order creation, a conditional PENDING-to-PAID update, and writing the order change, the entitlement, and an outbox event in one transaction.
Hint 4
Check prerequisites before creating the order, against the primary database rather than a cache or replica, so nobody pays and is then refused. Ask whether the check ever needs repeating at grant time.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and scale
I would agree on numbers first, for example:
- About 5,000 tenants; most small, a handful with 500k+ users.
- 10M registered users, ~1M daily active, ~100k courses.
- Browsing peaks around 20k QPS (read:write roughly 1000:1).
- Purchases: ~50/s average, ~500/s in promotions. Low volume, but each must be exactly right.
- Video: 200k concurrent streams at ~3 Mbps is about 600 Gbps, which is only feasible through a CDN.
Conclusion: reads must be cache- and CDN-friendly; the few writes can use a strongly consistent relational database.
2. API
The tenant always comes from the verified token claim or the tenant hostname, never from a body or query parameter.
| Endpoint | Purpose |
|---|---|
GET /v1/courses?cursor=&q= | Browse the tenant's catalog |
GET /v1/courses/{id} | Details, price, prerequisites |
POST /v1/orders (with Idempotency-Key) | Check prerequisites, create a PENDING order, return a gateway checkout session |
POST /v1/webhooks/payments | Gateway callback; verify signature first |
GET /v1/orders/{id} | Poll order status |
GET /v1/me/enrollments | List the learner's entitlements |
GET /v1/courses/{id}/content/{itemId} | Check entitlement, return a short-lived signed CDN URL |
POST /v1/courses/{id}/progress | Record progress and completion |
3. Data model
PostgreSQL, with tenant_id as the leading column of every primary key:
tenants(tenant_id, name, tier, region, db_cluster)
users(tenant_id, user_id, email, ...) UNIQUE(tenant_id, email)
courses(tenant_id, course_id, title, price, currency, status, version)
course_prereqs(tenant_id, course_id, prereq_course_id)
orders(tenant_id, order_id, user_id, status[PENDING|PAID|FAILED|REFUNDED],
amount, idempotency_key, gateway_ref, created_at)
UNIQUE(tenant_id, user_id, idempotency_key)
order_items(tenant_id, order_id, course_id, list_price, paid_price)
entitlements(tenant_id, user_id, course_id, order_id, granted_at, revoked_at)
PK(tenant_id, user_id, course_id)
progress(tenant_id, user_id, course_id, item_id, state, completed_at)
outbox(id, tenant_id, event_type, payload, published_at)
Media lives in object storage under /{tenant_id}/{course_id}/....
4. Architecture
CDN and WAF at the edge, then an API gateway that validates the JWT and injects tenant context. Behind it: Catalog (read-heavy, cached), Order/Payment, Entitlement, Progress, and Media (signs URLs). A cached Tenant Directory maps each tenant to its shard or cluster. Data sits in sharded Postgres (shard key tenant_id) with read replicas, Redis, and object storage. A transactional outbox feeds Kafka for cache invalidation, email, and analytics.
5. Isolation versus performance
| Model | Pros | Cons |
|---|---|---|
| Database per tenant | Strongest isolation, per-tenant backup/residency | Thousands of databases to operate; wasteful for small tenants |
Shared schema with tenant_id | Cheap, easy to scale | Noisy neighbours; one missing WHERE leaks data |
Recommendation: hybrid. Small tenants share sharded clusters; large or residency-bound tenants get dedicated ones. The Tenant Directory hides this so application code is identical.
Defense in depth: Postgres row-level security keyed on a per-connection app.tenant_id setting; a data-access layer that rejects unscoped queries; tenant-prefixed cache keys and storage paths.
Caching: Redis keys such as t:{tid}:course:{cid} with TTLs of minutes, invalidated by catalog events. CDN cache keys include the tenant host, so pages cannot cross tenants. Video and quiz assets are served via signed, short-lived URLs issued only after an entitlement check. Entitlements are cached per user (e.g. ent:{tid}:{uid}) with an hour-scale TTL, written through on grant and evicted on revoke.
6. Purchase consistency
POST /ordersverifies prerequisites and that the course is not already owned, inserts a PENDING order guarded by the idempotency key (retries return the same order), and opens a gateway session carrying theorder_id.- The webhook may be duplicated or out of order. Handle it in one transaction:
The conditional update makes it idempotent; the outbox guarantees the event is published if and only if the grant committed.UPDATE orders SET status='PAID', gateway_ref=$ref WHERE tenant_id=$t AND order_id=$o AND status='PENDING'; -- only if one row changed: INSERT INTO entitlements ... ON CONFLICT DO NOTHING; INSERT INTO outbox (...ENTITLEMENT_GRANTED...); - Instant access: the handler writes the entitlement through to Redis. If the learner returns before the webhook lands, the client polls the order. A reconciliation job asks the gateway about orders still PENDING after N minutes.
- Refunds: set
revoked_at, emit an event, evict the cache.
7. Prerequisite enforcement
- Check synchronously at order creation, reading from the tenant's primary database (not a replica or cache).
- Asynchronous validation is a mistake: the learner would pay and then be rejected, forcing a refund.
- Prerequisites form a per-tenant DAG; reject cycles when a course is authored. At purchase time, confirm
progress.completed_atis set for each direct prerequisite. - Re-checking at grant time is normally unnecessary because completion is monotonic. The exception is a policy where refunding a prerequisite revokes dependents; then re-check inside the grant transaction.
- Model admin overrides as explicit waiver rows rather than code-path special cases.
8. Trade-offs and common mistakes
- Trusting a tenant ID from the request instead of the token.
- Serving cached entitlements without a revoke path, so refunds do not take effect.
- Granting access on the redirect from the gateway rather than on the verified webhook.
- Non-idempotent webhooks that double-grant or double-email.
- Serving video from the origin, or CDN keys that omit the tenant.
- Checking prerequisites after payment.
- Putting a hot tenant on a shared shard with no way to migrate it out; the directory should make moves possible.
Accept eventual consistency for catalog and analytics; insist on strong consistency for orders and entitlements.