Front-End System Design for a Wikipedia-Scale Content Platform
A deep dive into designing a knowledge base with SSG-first architecture, full-text search, revision history, internationalization, and edge-cached content delivery.
SSGCDNFull-Text Searchi18nWikipedia-Scale
0. What Are We Building?
A global knowledge base serving 10k+ pages to users worldwide — think Wikipedia, but architected from the frontend perspective. The core challenge is not just building an article viewer; it is making content available instantly everywhere, handling edits from a small team of editors, and supporting search, revision history, multiple languages, and media embeds.
The problem statement comes with sharp constraints: 10 requests per second average, 40 rps peak, 100 rps burst from bots. SEO is mandatory — every page must be crawlable and LLM-friendly. Content must propagate globally within one hour of being published. And the entire system must be designed from the frontend out, with infra decisions serving the frontend architecture.
Key Insight
The golden rule for a knowledge base: by the time a user requests a page, all computation should already be done. No database queries, no server rendering — just a static file served from 200ms away. This rule drives every architectural decision.
1. Requirements & Scoping
A Wikipedia-scale knowledge base touches many subsystems. Here is how we scope it.
Functional
Article view and edit — wikitext/markdown with rich preview
Full-text search with typeahead, filters, and facets
Revision history — diff view, rollback, edit attribution
Category system — hierarchical content organisation
Internationalisation — multi-language articles, RTL support
Media embeds — images, video, PDFs with CDN optimisation
Non-Functional
Sub-2s page load on 3G — SSG + CDN with lazy media
Content propagation globally within 1 hour of publish
SEO friendly — semantic HTML, structured data, sitemaps
99.9% availability — CDN absorbs traffic, origin rarely hit
Tip
The 1-hour propagation SLA is the key design constraint. It dictates your build strategy (incremental, not full rebuild), your caching strategy (purge by URL, not flush-all), and your CDN strategy (global edge, not single-region).
2. Architecture — SSG-First, CDN-Everywhere
The architecture follows a "publish once, serve everywhere" model. Editors use a headless CMS to draft articles. When an article is published, a webhook triggers incremental static regeneration — only the changed page rebuilds, not all 10k.
SSG-first architecture — articles are pre-built, cached at the edge, updated incrementally
The build pipeline fetches the article content from the CMS API, runs it through a markdown-to-HTML parser, extracts metadata for search indexing, generates JSON-LD structured data, and writes the static HTML to the CDN. The entire pipeline for a single article takes 2-4 minutes — well within the 1-hour SLA.
CMS Choice
The editor experience should feel like Google Docs — rich text, image upload, drag and drop. Editors should never see markdown or JSON. Sanity is the right choice for this: concurrent editing is a first-class feature (Operational Transformation, same as Google Docs), it supports approval workflows out of the box, and it maintains full version history.
example.typescript
| CMS | Concurrent Editing | Versioning | Self-hosted | Use Case |
|------------|-------------------|------------|-------------|-------------------------|
| Contentful | Yes (conflict) | Full | No (SaaS) | Best UX, expensive |
| Sanity | Yes (real-time) | Full | No (SaaS) | Best for collaboration |
| Strapi | Limited | Yes | Yes | Self-hosted control |
| Directus | No | No | Yes | More data platform
Warning
Never design a content platform for technical users. The engineering-first approach — "just use Git for versioning, CI/CD for publishing" — breaks down when non-technical editors need to contribute. They cannot use Git, they cannot write markdown, and they should not have to.
Approval Workflow
Not every editor should publish directly. Implement a Draft → Review → Published pipeline:
example.typescript
Junior Editor → can create drafts, cannot publish
Senior Editor → can approve and publish
Admin → can do everything, unpublish, delete
When a junior submits for review:
→ Senior notified via Slack / email
→ Approval event logged with approver identity
→ Article moves to published state
→ Webhook triggers ISR rebuild
Incremental Builds — Meeting the 1-Hour SLA
Rebuilding 10k pages on every publish would take 30-40 minutes. Incremental builds are essential. When an article is published, the CMS fires a webhook containing the document ID and slug. The build pipeline fetches only that document, runs ISR revalidation for that specific path, and purges the CDN cache for that URL.
example.typescript
Webhook received:
{
"documentId": "article-abc123",
"slug": "/en/articles/understanding-quantum-computing",
"updatedAt": "2026-02-14T11:32:00Z"
}
Pipeline:
1. Fetch document from CMS API (single doc)
2. Build static HTML via SSG
3. Upload to CDN origin
4. Purge CDN cache for that URL
5. Update search index for that document
Total: 2-4 minutes
Key Insight
Next.js ISR + Cloudflare cache tags make this possible without a full rebuild. You call revalidatePath('/en/articles/my-post')via on-demand revalidation, and only that page is regenerated. The other 9,999 pages stay warm in the CDN.
3. Data Model
The data model for a knowledge base is straightforward but has several interconnected entities. The key entities are Article, Revision, Category, Media, and User.
The translations field on Article is a map of language codes to article IDs. This allows cross-linking between language variants without duplicating metadata. When rendering an article in French, the language switcher reads this map to offer all available translations.
Version Storage Strategy
Every update creates a full snapshot row in the database. Diffs are pre-computed for display only — never used for restore.
example.typescript
-- Live current state
articles
id, slug, title, body, current_revision_id, status
-- Every version ever saved
article_revisions
id, article_id,
body (JSONB),
editor_id, editor_name,
status (draft | in_review | published | archived),
change_summary,
created_at, published_at
-- Pre-computed diffs, display only
article_diffs
id, from_revision_id, to_revision_id,
diff (JSONB) -- never used for restore
Key Insight
Diffs are for display. Full snapshots are for restore. Never depend on diffs for data integrity. The schema stores full snapshots so restore is a single row fetch, then pre-computes diffs at save time so the version history UI can show changes instantly.
4. Interface Definition (API)
The API surface splits into three categories: article CRUD for the CMS, public read endpoints, and search/media APIs.
Public Article API
example.typescript
GET /api/articles/{slug}
→ Response: Article with rendered HTML body
→ Headers: Cache-Tag: article-{id}, lang-{lang}
→ Cache: stale-while-revalidate, CDN edge cache
GET /api/articles/{slug}/raw
→ Response: { title, body (markdown) }
→ For LLM crawlers and /raw endpoint
GET /api/articles/{slug}/revisions
→ Response: Revision[] (timeline metadata)
→ Each entry: { id, editor, timestamp, summary }
GET /api/articles/{slug}/revisions/{id}
→ Response: Full revision snapshot
GET /api/articles/{slug}/revisions/{from}/diff/{to}
→ Response: { diff: DiffEntry[] } (character-level)
→ Pre-computed, O(1) lookup
Search API
example.typescript
GET /api/search?q=quantum&lang=en&category=physics&page=1
→ Response: {
results: SearchResult[],
facets: { categories: Facet[], languages: Facet[] },
total: number,
page: number
}
→ Each result: { slug, title, excerpt, category, lang }
GET /api/search/suggest?q=quant
→ Response: string[] // typeahead completions
→ Powered by prefix index in Typesense
Media API
example.typescript
POST /api/media/upload
→ Body: multipart/form-data (file)
→ Response: { mediaId, url, thumbnailUrl, width, height }
→ Backend: resizes, uploads to R2, returns CDN URL
GET /api/media/{id}
→ Response: Media metadata + CDN URL
→ The actual file is served from CDN, not this endpoint
Tip
Keep the public API surface minimal. Most pages are pre-built HTML served from CDN and never hit an API. The API is for dynamic features: search, revision history, and media uploads. Every API call that can be avoided is a win for both latency and cost.
5. Article Rendering — Wikitext to HTML
Article rendering is the heart of a knowledge base. Raw wikitext must be parsed into structured HTML with a table of contents, cross-references, citation links, and media embeds.
Article rendering pipeline — wikitext is parsed to AST, then transformed into HTML with TOC and citations
Parsing Pipeline
example.typescript
function renderArticle(body: string): RenderedArticle {
// 1. Parse wikitext to AST
const ast = parseWikitext(body);
// AST: heading, paragraph, link, image, citation, list
// 2. Extract TOC from heading nodes
const toc = extractTOC(ast);
// [{ id: "intro", text: "Introduction", level: 2 }, ...]
// 3. Generate heading IDs for anchor links
assignHeadingIds(ast);
// 4. Resolve internal links (check slug exists)
resolveInternalLinks(ast, articleIndex);
// 5. Render citations as [1] [2] with tooltips
renderCitations(ast, citationData);
// 6. Transform media embeds to responsive <figure> elements
transformMediaEmbeds(ast);
// 7. Generate HTML string
const html = astToHTML(ast);
return { html, toc, citations, wordCount, readingTime };
}
Table of Contents
The TOC is built at build time by scanning the AST for heading nodes. Each heading gets a slugified ID (e.g., #introduction) that serves as both the TOC anchor and the URL fragment. The TOC is rendered as a sticky sidebar on desktop and a collapsible menu on mobile.
Citation System
Citations in wikitext use [ref] syntax. The parser extracts citation references, links them to a footnotes section at the bottom, and renders inline references as superscript links. On hover, a tooltip shows the citation preview. The citation data is embedded as JSON in the page HTML so no additional API call is needed.
Key Insight
The most common mistake in article rendering is doing it at request time. Render at build time. Every article page is a pre-rendered HTML file on the CDN. The TOC, citations, and media embeds are all baked into the static file. Zero computation at request time.
6. Search — Full-Text, Typeahead, Facets
Search in a knowledge base must be fast, relevant, and multi-lingual. We use Typesense (or Meilisearch) as a dedicated search engine — not Postgres full-text search, which struggles with fuzzy matching, typo tolerance, and relevance ranking at scale.
Search is the one endpoint that cannot be pre-rendered. It must be fast at the edge. Deploy the search API as a Cloudflare Worker that connects directly to Typesense, keeping the round-trip under 50ms. Never route search through your origin server.
7. Revision History — Diff, Rollback, Attribution
Every edit to an article creates a new revision. The revision history page shows a timeline of changes with who made them, when, and a summary of what changed.
Timeline View
example.typescript
Revision timeline display:
v12 — Published by Sarah Chen, 14 Feb 2026 11:32am ← current
"Fixed broken links in references section"
v11 — Edited by Rahul Mehta, 14 Feb 2026 10:01am
"Added section on quantum entanglement"
v10 — Published by Sarah Chen, 13 Feb 2026 4:45pm
"Initial version"
→ Click any revision to view full snapshot
→ Click "Compare" to see diff between two versions
→ One-click rollback restores any previous version
Diff Engine
Diffs are computed at save time using line-based diff (similar to Git's diff) and stored in the article_diffs table. The diff data includes added lines, removed lines, and unchanged context. The frontend renders these with green highlights for additions and red for removals.
Rollback is a single database write: copy the revision's body to the article's current body, create a new revision entry with a "Rolled back to revision N" summary, and trigger a revalidation webhook. No complex merge logic, no data reconstruction — full snapshots make rollback O(1).
Key Insight
Rollback is trivial only because we store full snapshots. If you store diffs (deltas), rolling back to version N means reconstructing state by applying versions 1 through N in sequence — fragile, slow, and error-prone. Full snapshots are cheap storage and priceless for reliability.
8. Internationalization
A global knowledge base must support multiple languages. Each article can have translations linked through the translations map. The language switcher reads this map and presents available translations.
URL Structure
example.typescript
/en/articles/quantum-computing ← English
/fr/articles/informatique-quantique ← French
/ja/articles/量子コンピューティング ← Japanese
/ar/articles/الحوسبة-الكمية ← Arabic (RTL)
URL mapping:
→ Slug is unique per language
→ /{lang}/articles/{slug}
→ hreflang tags in <head> link all variants
→ Canonical URL points to the default language (usually English)
Arabic, Hebrew, and Persian require right-to-left layout. The page <html> tag sets dir="rtl" based on the language code. All layout CSS uses logical properties margin-inline-start, padding-inline-end — never hardcoded left/right. The TOC sidebar moves to the right side in RTL mode.
Tip
Use logical CSS properties from the start. Retrofitting RTL support is painful if you have margin-left scattered across 200 components. Properties like inset-inline-start automatically flip in RTL mode with zero extra code.
Translation Management
Translations are managed through the CMS as separate documents linked by the translations field. Each translation has its own revision history, its own editor workflow, and its own publish state. An article can be published in English while the French translation is still in draft.
Key Insight
Do not try to keep translations in sync automatically. A change to the English article does not automatically update the French version. Instead, the CMS shows a "translation needs update" indicator on the French article when the source English article changes. The translator decides when to publish.
9. Performance Optimization
A global knowledge base must load fast everywhere — from a fiber connection in Tokyo to 3G in rural India. The optimization strategy works at multiple layers simultaneously.
Layer 1: CDN — Serve from the Nearest Edge
Cloudflare operates 200+ PoPs globally. A user in Mumbai hits the Mumbai PoP at ~5ms latency. A user in rural Germany hits Frankfurt at ~3ms. Without a CDN, a single origin in US-East would serve those users at 180-220ms.
A service worker caches article pages for offline access. On flaky networks, previously visited pages load instantly from cache while the worker updates in the background.
example.typescript
// service-worker.js
// HTML pages — StaleWhileRevalidate
workbox.routing.registerRoute(
({ request }) => request.destination === 'document',
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'pages-cache'
})
);
// Images — CacheFirst with 30-day expiry
workbox.routing.registerRoute(
({ request }) => request.destination === 'image',
new workbox.strategies.CacheFirst({
cacheName: 'images-cache',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 200,
maxAgeSeconds: 30 * 24 * 60 * 60,
}),
],
})
);
// Search API — NetworkFirst with 3s timeout
workbox.routing.registerRoute(
({ url }) => url.pathname.startsWith('/api/search'),
new workbox.strategies.NetworkFirst({
cacheName: 'api-cache',
networkTimeoutSeconds: 3,
})
);
Key Insight
The most impactful performance optimization for a knowledge base is CDN cache hit rate. Every request that hits the edge instead of the origin saves 150-200ms of latency. Target 95%+ cache hit rate for article pages. This is achievable with SSG + smart cache tags + stale-while-revalidate.
10. Security
A knowledge base with user-generated content, file uploads, and rich text rendering has a large attack surface. Here is how we lock it down.
XSS in Wikitext
The wikitext parser strips all raw HTML tags except a tiny allowlist. Even in markdown mode, the rendered HTML passes through DOMPurify before being served to users. Links are validated — javascript: and data: URLs are rejected.
Since only authenticated editors can edit, spam is less of a concern than on Wikipedia. However, we still rate-limit the CMS API: 10 edits per minute per editor. Sudden bursts trigger a Turnstile challenge. The approval workflow means no change goes live without a senior editor's review.
CSRF and API Protection
All API mutations require a CSRF token. The token is issued with the session cookie and validated server-side. The search and article APIs are read-only and publicly accessible, but rate-limited to 100 requests per minute per IP.
Rate Limiting Strategy
example.typescript
Known bot signatures → 100 rps token bucket, then 429
Regular users → 40 rps per IP, sliding window
Editor IPs (allowlisted) → no rate limit
DDoS threshold → auto-challenge with Turnstile at 150+ rps
Warning
Never trust client-side sanitization alone. Sanitize on both client (for immediate feedback) and server (for enforcement). A malicious editor could bypass the client-side sanitizer and send raw HTML directly to the API. Server-side DOMPurify is your last line of defence.
11. Testing Strategy
A content platform that serves millions of requests across 200+ edge locations needs testing at every layer — from unit tests on the wikitext parser to synthetic monitoring on live CDN endpoints.
Parser Tests
The wikitext parser is tested with a corpus of known article markdown. Each test asserts that a given markdown input produces the expected AST and HTML output. Edge cases include nested lists, mixed RTL/LTR text, malformed citations, and injection attempts.
Snapshot tests verify that article components render correctly across languages and categories. Each test renders a known article fixture and asserts the DOM structure, TOC links, and citation footnotes.
Search Relevance Tests
A set of known queries with expected results. For example, searching "quantum computer" should return the quantum computing article as the first result. These tests run against a test search index seeded with sample data.
Accessibility Audits
Every PR runs axe-core against article pages, search results, and the revision history view. The TOC, language switcher, and citation tooltips must be fully keyboard-accessible.
Synthetic Monitoring
Checkly runs real browser tests every 60 seconds against the top 100 article pages across 5 geographic regions. Alerts fire if page load exceeds 4s, if status is not 200, or if the CDN cache hit rate drops below 90%.
12. Accessibility
A knowledge base is a reference resource — it must be usable by everyone, including screen reader users, keyboard-only users, and users with cognitive disabilities.
Skip Navigation: A .skip-link at the very top of the page lets keyboard users jump directly to the main content.
Semantic HTML: Articles use <article>, the TOC uses <nav aria-label="Table of contents">, and headings use proper h1-h6 hierarchy.
Keyboard Navigation: The TOC, language switcher, search results, and revision timeline are fully navigable with Tab and Arrow keys.
Focus Management: When navigating between articles via the TOC, focus moves to the article title. When a search is performed, focus lands on the first result.
Live Regions: Search results update an aria-live="polite" region so screen readers announce new results without interrupting the current task.
Images: Every article image requires an alt text. The CMS enforces this at edit time. Decorative images use alt="".
Color Contrast: All text meets WCAG 2.1 AA contrast ratios. The TOC, citation links, and category badges are tested with contrast checkers in CI.
Tip
The citation tooltip is the most commonly broken accessible component in knowledge bases. Ensure it can be opened with Enter, closes with Escape, and does not trap focus. Use role="tooltip" with aria-describedby on the citation link.
13. Key Takeaways
Seven things to remember when building a Wikipedia-scale knowledge base:
SSG-first, CDN-everywhere
Pre-render all article pages at build time. Serve static HTML from CDN. Zero compute at request time for content pages.
Incremental builds, not full rebuilds
A single article update rebuilds one page, not 10k. ISR + webhooks keep the 1-hour SLA without a 40-minute build.
Full snapshots for revisions, diffs for display
Store every revision as a full snapshot. Pre-compute diffs at save time. Rollback is a single row fetch — never reconstruct state from deltas.
Search is the only uncacheable endpoint
Everything else is pre-rendered or cached. Search demands a dedicated engine (Typesense/Meilisearch) deployed at the edge as a Worker.
Logical CSS for i18n from day one
Use margin-inline-start, padding-inline-end — never left/right. RTL support becomes a dir attribute change, not a layout rewrite.
Sanitize at build time
XSS sanitization runs during SSG, not at request time. The static HTML is already clean. No per-request sanitization overhead.
Monitor three layers: CDN, app, and user
Cloudflare Analytics for CDN health, Sentry for JS errors, Checkly for synthetic user journeys. No single tool covers all failure modes.