System Design · Worked case study
Designing Search for Educational Videos
Build a searchable educational-video catalog with controlled ingestion, fresh indexes, authorization-aware results, stable pagination, and measurable ranking quality.
Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.
Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.
What you will be able to explain
- Estimate catalog ingestion, indexing, and query workloads with units and growth headroom.
- Design an index pipeline that tolerates retries and makes freshness observable.
- Explain authorization-aware ranking and pagination that remain stable while content changes.
Define searchable content and product behavior
Design a YouTube-style educational-video search product: a learner enters words or phrases and receives relevant published lessons with title, instructor, course, duration, level, language, captions, and a short description. The product-style label describes only the learner experience; this is an original design, not an account of any company's architecture. Filters include subject, level, duration band, language, and publication date. Assume 8 million registered learners, 1 million monthly active users, and 5 million catalog items including episodes, transcripts, and course records. Exclude video hosting, recommendation feeds, real-time co-watching, paid checkout, and arbitrary user-generated uploads; this system searches metadata and authorized transcript text while a separate media platform serves playback. Public lessons are visible to everyone; draft, course-enrolled, age-restricted, or region-restricted items require authorization. Relevance can be personalized modestly by declared learning level, but must not silently make private history part of the query. A catalog editor expects newly published lessons to appear within two minutes most of the time, while unpublishing or access revocation should take effect more quickly through a denylist or authoritative check. Search results are best-effort snapshots, not a transactionally frozen catalog. Explain that relevance scores can change when ranking signals or index versions change, and offer deterministic tie-breaking for pagination.
Estimate writes, index size, and search demand
Suppose 1 million monthly active learners generate 8 searches each per day on 20 active days: 160 million searches monthly, about 62 queries/s averaged over 30 days. A 15× peak gives about 930 QPS. Each search can fan out across title, description, transcript, and filters, so benchmark actual multi-field queries rather than assuming one field lookup. For ingestion, 5 million catalog items averaging 2 KiB of normalized metadata occupy about 10 GiB raw; token dictionaries, postings, stored fields, replicas, and segment merge overhead may multiply this by 3–6×, so budget 30–60 GiB for one index generation, plus blue/green rebuild overlap. If 50,000 lessons update daily and each produces a 4 KiB change event, event traffic is only about 2.3 events/s on average but bulk transcript imports can create bursts of 100,000 documents/hour, or 28/s. The bottleneck may be analyzing long transcripts and merging index segments rather than event count. Reserve 30% CPU and disk headroom, maintain space for a new index version during reindexing, and protect query capacity from ingestion jobs. Measure median and p99 transcript size, language distribution, and burst patterns; large descriptions or malformed subtitles can dominate memory and query latency.
| Workload | Calculation | Capacity implication |
|---|---|---|
| Query average | 160M / (30 × 86,400) ≈ 62/s | Benchmark at 930 QPS peak |
| Metadata raw size | 5M × 2 KiB ≈ 10 GiB | Plan 30–60 GiB per generation including index overhead |
| Bulk import | 100,000 / 3,600 ≈ 28 docs/s | Separate ingestion throttling from interactive queries |
| Reindex overlap | Old + new generation | Reserve duplicate disk and rollback window |
Start as one catalog application and evolve the index boundary
The first version can be a catalog application with PostgreSQL as the source of truth and a managed search index as a derived projection. Editors publish through the application; a transactional outbox records catalog changes, and a worker applies them to the index. This small architecture is easier to debug than dual writes inside an HTTP request. It becomes strained when catalog transactions wait on indexing, full transcript processing consumes API resources, or search and content editing need different scaling. The evolved system separates catalog APIs, ingestion workers, an event stream, an indexer, and query-serving search nodes. The database remains authoritative for publication state and permissions; the search index accelerates retrieval but can lag or be rebuilt. A content change gets a monotonically increasing version per item. The indexer ignores an older event arriving after a newer version, making retries and reordering safe. Query nodes can be replicated by region and use an alias to switch between index generations. Do not copy permissions into an index and trust them indefinitely: access can be revoked while a document remains indexed. The query service combines indexed candidate retrieval with current visibility checks or an explicit authorization filter whose staleness is tightly bounded. A queue absorbs bursts but must not conceal a growing watermark gap.
Creates and publishes lesson metadata
Validation, source-of-truth writes, visibility policy
Versioned items and transactional outbox
Durable events, keyed by item ID
Normalize text, captions and metadata; reject stale versions
Derived candidates and relevance fields
Authorization filter, ranking and cursor construction
Searches, filters and paginates
- Catalog editor → Catalog API: publish changes
- Catalog API → Catalog database: commit item + outbox
- Catalog database → Change stream: relay event
- Change stream → Indexing workers: at-least-once delivery
- Indexing workers → Search index: versioned upsert/delete
- Learner → Search API: query and cursor
- Search API → Search index: candidate retrieval
- Search API → Catalog database: current visibility check
Design query and index contracts
POST /v1/search accepts query text, filters, locale, learner context only when consent permits, page size up to 50, and an opaque cursor. The response includes result IDs, authorized display fields, stable cursor, index generation, and a freshness timestamp; it does not expose raw relevance scores as promises. GET /v1/items/{id} remains the authoritative detail path. Editor APIs publish or unpublish with an expected item version. Normalize each item into SearchDocument(itemId, version, title, description, transcript segments, topicIds, level, language, durationSeconds, publishedAt, visibilityPolicyRef, regionRules, contentHash). Keep transcript segment offsets so a result can show a relevant excerpt and jump-to-time. The index stores an analyzer version and source version; a delete tombstone must survive long enough that an older delayed upsert cannot resurrect content. For pagination, sort by a composite such as relevance score, published timestamp, item ID, and include all sort values in a signed cursor along with normalized query, filter hash, generation, and expiry. Reject a cursor if the query or filters differ. If the index generation changes, either retain the old generation briefly for cursor continuity or return a restart-pagination response. Never trust a client-supplied user role: authorization context comes from the authenticated server session.
json · Illustrative example; validate before production use
{"query":"distributed tracing","filters":{"level":"intermediate","language":"en"},"limit":20,"cursor":null}
{"items":[{"id":"lesson-82","title":"Tracing a Queue Consumer","durationSeconds":840,"level":"intermediate","match":{"kind":"transcript","startSeconds":211}}],"nextCursor":"signed-opaque-token","indexGeneration":"catalog-v18","indexedThrough":"2026-11-08T19:00:00Z"}Trace publication, indexing, search, and revocation
When an editor publishes a lesson, the catalog database validates required fields, writes the new source version, and appends an outbox event in one transaction. A relay publishes at least once. The index worker fetches canonical content rather than trusting an incomplete event, extracts transcript text, normalizes language and fields, checks size and malware policies for attachments, and upserts only if its version exceeds the indexed version. It records processing outcomes and advances a partition watermark only after durable index acknowledgement. Search parses and normalizes a learner query, validates filters, applies authorization constraints, retrieves a bounded candidate set, and ranks candidates. Before returning protected results it verifies current visibility state in batch; if that check is unavailable, fail closed for restricted content while public results may continue. Pagination uses the signed continuation state rather than a large offset. On unpublish or revocation, write a tombstone and invalidate any result cache; a query-time visibility check closes the race while the tombstone propagates. Search analytics should record query category and result interactions only under an explicit privacy policy, with identifiers minimized and retention bounded. If a document fails indexing, keep it in a retryable dead-letter state and expose the source version and error class to editors; silently skipping it would make freshness appear better than it is.
Sends query and signed cursor
Validates session, filters, query and cursor
Search index ranks bounded result set
Current access, region and publication state
Stable tie-break and opaque cursor
Only visible metadata and transcript excerpts
- Learner client → Search API: HTTPS search
- Search API → Candidate retrieval: normalized query
- Candidate retrieval → Visibility check: candidate IDs
- Visibility check → Page builder: authorized subset
- Page builder → Authorized results: results + cursor
Balance relevance, freshness, and authorization
A transparent baseline ranks exact title matches, phrase matches, topic matches, and transcript matches, then applies modest boosts for recency, completion quality, or a learner's explicitly selected level. Avoid making watch history a hidden proxy for ability or personal identity. Score formulas are hypotheses to validate with labeled query sets and human review, not objective truth. Measure recall@k for known useful items, nDCG@k for graded relevance, zero-result rate, reformulation rate, and successful lesson starts. Slice by language, accessibility caption availability, level, and public versus enrolled content to detect systematic gaps. Authorization must be applied before snippets leave the service: filtering after the response is constructed can leak a private title through a preview, cache, or log. A stale search index may include a deleted item; a current policy check or revocation cache with a strict invalidation guarantee is required. If the policy service fails, use an explicit fail-closed fallback for restricted material and an agreed availability fallback for public content. Pagination is not a frozen snapshot unless the index offers one. New documents can shift scores between requests, so a cursor should bind to a generation and sort tuple; clients can still see occasional changes if that generation is retired. Explain this behavior and offer a restart path rather than silently skipping or duplicating results.
- Use explicit evaluation sets and a documented ranking version for each index generation.
- Treat permission as a hard constraint, never as a ranking signal.
Make freshness and pagination recoverable
At-least-once ingestion means the indexer must be idempotent by item ID and source version. If event version 12 arrives before version 11, version 11 is ignored. Deletes need versioned tombstones because physically deleting a document immediately can let an old retry recreate it. A periodic consistency scan compares canonical item versions and visibility with indexed versions, repairing missing, stale, or orphaned records. Watermarks should be tracked per event partition and interpreted carefully: a recent watermark does not prove every item was indexed if a poison event blocks or is skipped. Dead letters require retry budgets, replay tooling, and alerts. For a stable page, use deterministic tie-breaking and a cursor signed against tampering; bind it to normalized query, filters, user authorization scope, sort values, generation, and expiration. A cursor must not become an authorization token: every page rechecks the caller. If access changes halfway through pagination, removing newly forbidden records may make a page shorter; do not fill it from unauthorized candidates. Search index snapshots or point-in-time handles help stable traversal but consume resources and need expiration. For concurrent publishes, the next page can omit a newly inserted high-ranked item until the learner restarts; this is acceptable when stated. Verify no item appears twice across adjacent pages for an unchanged generation and stable data set.
| Condition | Correctness rule | Repair |
|---|---|---|
| Duplicate event | Apply one source version at most | Idempotent versioned upsert |
| Out-of-order update | Never replace newer indexed version | Compare version and retain tombstone |
| Cursor from another query | Reject; do not reinterpret | Bind cursor to query and filter hash |
| Revoked access | Do not return stale candidate or snippet | Current authorization check and cache invalidation |
Handle index, region, and dependency failures
If the indexer falls behind, continue serving the last known generation only if its age remains within the published freshness objective; show an internal freshness warning and alert on lag. If indexing capacity is exhausted during a bulk import, throttle imports rather than allowing search query latency to collapse. If a search cluster fails, route to a healthy replica or a prior index generation and degrade optional personalization first. If authorization checks fail, restricted results fail closed; a public-only fallback may be offered only when scope is provably public. On regional failure, read replicas of the index can serve search, but catalog edits must have one authoritative write region or a conflict protocol. An index is rebuildable, but source catalog, access rules, transcript assets, and deletion tombstones are not interchangeable. A rebuild should consume a consistent source snapshot plus change stream from a checkpoint, then catch up before alias swap. Keep the prior generation until validation and rollback period end. If a region has stale content after failover, current visibility checks still protect private items, while freshness metrics expose public lag. Document recovery point objectives for catalog updates separately from index freshness. A restore drill should include authorization data and test a revoked private item, because a technically healthy search result can still violate confidentiality.
| Failure | Degraded mode | Recovery guard |
|---|---|---|
| Indexing backlog | Serve last generation within freshness limit | Alert on oldest event and per-partition watermark |
| Search node loss | Fail over or use previous generation | Verify query and auth policy versions |
| Policy lookup outage | Fail closed for restricted results | Restore policy service and test revoked content |
| Region loss | Promote single catalog writer; rebuild derived index | Checkpoint catch-up and authorization audit |
Treat queries, transcripts, and results as sensitive
Validate query length, token count, filter cardinality, and wildcard or regex features; expensive query constructs can become denial-of-service vectors. Enforce per-account and per-IP rate limits, with fair handling for shared networks. Do not return private course titles, transcript fragments, or even counts to an unauthorized user. Signed cursors prevent tampering but must not reveal internal shard details. Escape snippets for HTML and preserve text-only rendering for transcript content. Search terms may reveal health, employment, or learning interests; minimize collection, aggregate analytics, and offer clear retention and consent choices. Editors need role-based permissions, audit logs, review for bulk publication, and a safe unpublish mechanism. Restrict index administration and protect snapshots because indexes duplicate source data. Source links and external captions require validation to prevent unsafe URLs or injected markup. Provide abuse reporting for impersonation or harmful educational material and an editorial process for removal. Keep personal learner signals separate from catalog metadata and do not write full raw queries into tracing spans. Security and privacy testing includes unauthorized filters, cursor replay under a different user, hidden snippets, deletion resurrection, query resource exhaustion, and index snapshot access.
- A search result's existence can itself disclose restricted content; counts and facets need authorization too.
- Define deletion propagation across source records, indexes, caches, analytics, and backups.
Set SLOs and ranking measurements
An availability indicator should measure valid search requests that return an authorized, usable result page, not merely HTTP 200 responses. An initial target could be 99.9% monthly availability, p95 under 350 ms and p99 under 900 ms at the documented peak. Freshness is separate: 95% of successful publication updates searchable within two minutes and 99% within ten minutes. Track partition watermark age, indexer retry age, dead-letter count, index build duration, disk headroom, query latency by query class, authorization-check failures, cursor rejection rate, and zero-result rate. A ranking launch needs offline relevance evaluation and a low-risk online experiment with guardrails for latency, access leakage, and result diversity. Search success should be measured using aggregate interaction events only with consent and privacy review. Separate public and protected query availability, because one policy dependency can affect the latter differently. Define alert thresholds from error-budget burn and freshness objectives; a quiet queue with skipped poison events is not healthy. Run canary queries that include an item just published, an unpublish action, a private item as an unauthorized user, and multiple pagination pages. Record the index generation and analyzer version on each response for diagnosis without exposing them as ranking guarantees.
| SLO | Measurement | Initial target |
|---|---|---|
| Query page latency | API start to authorized response | p95 < 350 ms; p99 < 900 ms |
| Publish freshness | Commit to queryable indexed version | 95% < 2 min; 99% < 10 min |
| Authorization leakage | Restricted result or snippet exposed | Zero confirmed incidents |
Estimate cost and evolve with reversible indexes
A hypothetical monthly deployment might spend $9,000 on three replicated search nodes with enough RAM and disk for a blue/green index, $4,000 on catalog database and replicas, $3,000 on transcript ingestion and event processing, $4,000 on query APIs and cache, and $3,000 on logs, backups, and monitoring: about $23,000 before engineering labor and data transfer. The largest uncertainty is index replication and transcript growth; benchmark representative languages and compression. A relational full-text search may be sufficient for a small catalog and avoids a second indexing system, but complex ranking, transcript retrieval, and high query concurrency can justify a dedicated engine. A hosted search provider reduces cluster operations but creates cost, data-residency, and portability concerns. Begin migration when measured query latency or ranking needs exceed the simpler design. Build a parallel index, replay catalog events from a known checkpoint, compare item coverage, access filters, and relevance against fixed evaluation queries, then switch a small traffic percentage with an alias. Keep the old generation for rollback and do not dual-write independently from API handlers. Rebuilds should be repeatable from source snapshots plus ordered changes. Interview follow-ups include multilingual tokenization, typo tolerance, transcript timestamp ranking, deletion guarantees, personalized ranking ethics, and what happens when the policy service is down.
- Track cost per thousand searches and per indexed catalog item, including rebuild overlap.
- Version analyzers, ranking rules, and source schemas so rollbacks are testable.
Terms in plain language
- Ingestion watermark
- A record or timestamp showing how far the index pipeline has processed source changes.
- Visibility filter
- A query-time condition that ensures only content currently visible to the requesting user can be returned.
- Search-after cursor
- A continuation token based on the last result's sort values, avoiding offset scans for deep pages.
- Index lag
- Time between an authoritative catalog change and its visibility in a searchable index.
Capacity lab
Change the assumptions and inspect the math. This teaching model assumes every request creates one stored record. Real systems separate reads, writes, uploads and background work.
- Average QPS
- 231.48
- daily users × requests per user / 86,400
- Peak QPS
- 1,157.41
- average QPS × peak multiplier
- Peak payload bandwidth (MB/s)
- 1.16
- peak QPS × bytes/request / 1,000,000
- Logical retained storage (GB)
- 600
- requests/day × bytes/request × retention / 1,000,000,000
- Replicated storage (GB)
- 1,800
- logical storage × stored copies
- Serving nodes
- 1
- ceil(peak QPS / (node throughput × utilization))
Decimal MB/GB, not MiB/GiB. Indexes, protocol overhead, compression, retries, backups and failover capacity are excluded. Measure throughput on your workload; this is not a sizing guarantee or a cloud price quote.
References and boundaries
Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.
Documents pagination approaches including search_after; it does not establish authorization or ranking guarantees for this hypothetical system.
Describes messaging delivery and processing semantics relevant to an ingestion pipeline, not this catalog's end-to-end freshness.
An authoritative alternative for basic full-text search; it does not validate the proposed dedicated index architecture.