Files
tiago-neves 1e3e6b1a3e
Tests / bridge tests (push) Successful in 1m1s
Tests / writer-pipeline tests (pull_request) Successful in 55s
Tests / writer-pipeline tests (push) Successful in 1m3s
Tests / bridge tests (pull_request) Successful in 57s
Tests / frontend lib tests (pull_request) Successful in 57s
Tests / frontend lib tests (push) Successful in 1m4s
docs: close BIT-28133 — architecture.md TTFB contract + PROJECT_STATUS status sync
architecture.md §6 still stated the aspirational <30ms Cloudflare-HIT
target as if it were the production contract; PERFORMANCE_BASELINE.md
and PROJECT_STATUS.md were already revised to the measured <150ms
Free-plan contract via #40/#44 but this table was missed. Also flips
the two BIT-28133 status cells in PROJECT_STATUS.md from in_review to
done now that the contract is reconciled everywhere.
2026-08-05 06:21:22 +01:00

416 lines
18 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# News Platform — Architecture
**Version:** 1.0
**Date:** 2026-03-23
**Author:** David Santos (Founding Engineer, BitReport)
---
## Overview
A scalable, multi-domain news platform designed for high traffic. Built on a headless architecture: Astro 5 SSR frontend, Fastify bridge layer, and WordPress as the headless CMS. The platform supports multiple domains without code changes — only per-domain JSON config files need to be added.
---
## 1. Stack Selection and Justification
### Decision: Astro 5 SSR + Fastify Bridge + Headless WordPress
#### Framework Comparison
| Criterion | Astro 5 SSR | Next.js 15 | Nuxt 3 |
|-----------|-------------|------------|--------|
| Default output | Static/SSR hybrid | SSR/CSR | SSR/CSR |
| JS sent to client | Near-zero by default | Significant (React hydration) | Moderate (Vue hydration) |
| TTFB (cached SSR) | Excellent | Good | Good |
| Core Web Vitals (CLS/LCP) | Best (minimal hydration) | Moderate (layout shift on hydrate) | Moderate |
| Multi-framework components | Yes (React, Vue, Svelte) | React only | Vue only |
| Static island hydration | Built-in (Islands Architecture) | Manual (RSC) | Manual (Suspense) |
| Cold-start (serverless) | Lower (small runtime) | Higher (React + Next core) | Moderate |
| SEO primitives | First-class | Good | Good |
| Build size | Minimal | Large | Moderate |
| Ecosystem maturity | Growing, stable API | Mature | Mature |
**Why Astro 5 wins for a news platform:**
1. **Islands Architecture by default.** The vast majority of a news page is static content (headline, article body, images). Astro only ships JS for interactive islands (e.g., search widget, ad slots). This directly improves LCP and TBT.
2. **Near-zero JS on article pages.** Article pages account for ~90% of traffic on news sites. No hydration penalty means better Core Web Vitals at scale.
3. **CDN/cache friendliness.** Astro pages render to clean HTML + minimal CSS. CDN edge caches store full responses. No runtime client-side fetch waterfalls.
4. **Content Collections and SSR together.** Astro 5's SSR mode supports per-request server rendering while still allowing static prerendering for high-volume pages. Hybrid SSR/static per route.
5. **Performance targets are achievable.** TTFB < 200 ms cached, LCP < 2.5 s, CLS < 0.1 are all attainable with Astro's default output. Next.js requires additional tuning (turbopack, RSC, `use client` discipline) to reach the same floor.
6. **Multi-domain config is simple.** Astro reads domain from `Astro.request.headers.get('host')` in SSR mode — no framework-specific routing hacks needed.
**Next.js trade-offs (why not chosen):**
- React hydration by default inflates JS payload
- App Router complexity (RSC + Server Actions) adds cognitive overhead not needed for a content site
- Bundle size is higher even for static pages
**Nuxt trade-offs (why not chosen):**
- Vue ecosystem is smaller than React; fewer available UI component libraries for news/media layouts
- SSR cold start slightly heavier than Astro
---
## 2. Component Diagram
```
┌─────────────────────────────────────────────────────────────────┐
│ User / Browser │
└─────────────────────────┬───────────────────────────────────────┘
│ HTTPS
┌─────────────────────────▼───────────────────────────────────────┐
│ Cloudflare CDN / Edge Cache │
│ (full-page HTML cache, static assets, image transforms) │
└─────────────────────────┬───────────────────────────────────────┘
│ Cache miss / dynamic
┌─────────────────────────▼───────────────────────────────────────┐
│ Nginx Reverse Proxy (LXC) │
│ (TLS termination, host routing → port 4321) │
└─────────────────────────┬───────────────────────────────────────┘
│
┌─────────────────────────▼───────────────────────────────────────┐
│ Astro 5 SSR Frontend (:4321) │
│ │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ Domain config│ │ Page routes │ │ Island components │ │
│ │ loader │ │ / │ │ (search, comments, │ │
│ │ │ │ /[category] │ │ ad slots, menus) │ │
│ └─────────────┘ │ /[cat]/[slug]│ └──────────────────────┘ │
│ │ /sitemap.xml │ │
│ │ /robots.txt │ │
│ └──────────────┘ │
└─────────────────────────┬───────────────────────────────────────┘
│ HTTP (internal)
┌─────────────────────────▼───────────────────────────────────────┐
│ Fastify Bridge (:3200) │
│ │
│ ┌───────────────┐ ┌─────────────┐ ┌────────────────────┐ │
│ │ Domain → WP │ │ Redis cache │ │ Data normalizer │ │
│ │ router │ │ layer │ │ (WP → canonical │ │
│ │ │ │ (TTL: 60s) │ │ article model) │ │
│ └───────────────┘ └─────────────┘ └────────────────────┘ │
│ │
│ Routes: GET /posts GET /posts/:slug GET /categories │
│ GET /tags GET /search GET /sitemap │
└─────────────────────────┬───────────────────────────────────────┘
│ HTTP
┌─────────────────────────▼───────────────────────────────────────┐
│ WordPress (headless, nginx :8080 → PHP-FPM) │
│ │
│ REST API /wp-json/wp/v2/ │
│ posts, categories, tags, media, users │
│ │
│ No theme rendered — WP admin only for editorial. │
└─────────────────────────┬───────────────────────────────────────┘
│
┌─────────────────────────▼───────────────────────────────────────┐
│ Redis (:6379) │
│ Bridge response cache (articles, category lists, menus) │
└─────────────────────────────────────────────────────────────────┘
```
---
## 3. Data Flow
### Standard Article Page Request
```
Browser
→ GET https://newsproject.bitreport.pt/futebol/porto-bate-benfica
→ Cloudflare CDN checks edge cache
HIT → return cached HTML (TTFB: ~10–30 ms)
MISS → forward to Nginx
→ Nginx → Astro SSR (:4321)
→ Astro reads host header
→ Loads config/domains/newsproject.bitreport.pt.json
→ Fetches article: GET http://bridge:3200/posts?slug=porto-bate-benfica&domain=newsproject.bitreport.pt
→ Fastify Bridge checks Redis key posts:newsproject:porto-bate-benfica
HIT → return normalized article (TTFB bridge: ~2 ms)
MISS → GET http://wp.newsproject.local/wp-json/wp/v2/posts?slug=porto-bate-benfica
→ normalize response
→ write to Redis (TTL: 60 s)
→ return to Astro
→ Astro renders full HTML page (SSR)
→ Sets Cache-Control: s-maxage=60, stale-while-revalidate=300
→ Cloudflare caches response
→ HTML returned to browser
```
### Cache Invalidation
On WordPress `save_post` hook, a custom plugin calls:
```
POST http://bridge:3200/cache/invalidate
{ "domain": "newsproject.bitreport.pt", "slug": "porto-bate-benfica" }
```
This deletes the specific Redis keys and optionally triggers a Cloudflare Cache Purge API call.
---
## 4. Multi-Domain Routing
### Config File Structure
```
config/
domains/
newsproject.bitreport.pt.json
sports1.example.com.json
```
### Domain Config Schema
```jsonc
{
"site_name": "Sports News",
"site_description": "The best sports coverage in Portugal",
"theme": "sports",
"logo": "/assets/newsproject/logo.svg",
"favicon": "/assets/newsproject/favicon.ico",
"primary_color": "#e63946",
"categories": ["Football", "Basket", "F1", "Tennis", "Rugby"],
"nav_categories": ["Football", "Basket", "F1"],
"wp_endpoint": "http://wp.newsproject.local/wp-json",
"bridge_endpoint": "http://bridge:3200",
"locale": "pt_PT",
"timezone": "Europe/Lisbon",
"social": {
"twitter": "@sportsbitreport",
"facebook": "sportsbitreport"
},
"ads": {
"enabled": false,
"provider": null
},
"analytics": {
"ga4": null
}
}
```
### Astro Domain Resolution (SSR)
```typescript
// src/lib/domain.ts
export async function loadDomainConfig(host: string) {
const sanitized = host.replace(/:\d+$/, ""); // strip port
const configPath = path.join("config/domains", `${sanitized}.json`);
if (!existsSync(configPath)) {
throw new Error(`No domain config found for: ${sanitized}`);
}
return JSON.parse(readFileSync(configPath, "utf-8")) as DomainConfig;
}
```
Adding a new domain requires only:
1. Create `config/domains/<new-host>.json`
2. Configure DNS → same server
3. No code changes, no redeploy required (file is read at request time in SSR mode)
---
## 5. SEO Strategy
### Server-Side Rendering
All pages are fully rendered server-side. Search engine crawlers receive complete HTML on first request — no JS execution required for indexing.
### Schema.org Structured Data
Article pages emit `NewsArticle` JSON-LD:
```json
{
"@context": "https://schema.org",
"@type": "NewsArticle",
"headline": "Porto bate Benfica no clássico",
"datePublished": "2026-03-23T12:00:00Z",
"dateModified": "2026-03-23T13:30:00Z",
"author": { "@type": "Person", "name": "João Silva" },
"publisher": {
"@type": "Organization",
"name": "Sports News",
"logo": { "@type": "ImageObject", "url": "https://newsproject.bitreport.pt/logo.png" }
},
"image": "https://newsproject.bitreport.pt/img/porto-benfica.jpg",
"url": "https://newsproject.bitreport.pt/futebol/porto-bate-benfica"
}
```
### URL Structure
```
/ Homepage
/[category]/ Category page
/[category]/[slug]/ Article page
/sitemap.xml Sitemap (generated dynamically from bridge)
/robots.txt Robots (generated per domain config)
/search?q=porto Search results (SSR + client island)
```
### Meta Tags (per page)
```html
<title>{title} | {site_name}</title>
<meta name="description" content="{excerpt}" />
<link rel="canonical" href="{canonical_url}" />
<!-- Open Graph -->
<meta property="og:type" content="article" />
<meta property="og:title" content="{title}" />
<meta property="og:description" content="{excerpt}" />
<meta property="og:image" content="{featured_image}" />
<meta property="og:url" content="{canonical_url}" />
<meta property="og:site_name" content="{site_name}" />
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="{title}" />
<meta name="twitter:description" content="{excerpt}" />
<meta name="twitter:image" content="{featured_image}" />
```
---
## 6. Performance Targets
| Metric | Target | Strategy |
|--------|--------|----------|
| TTFB (cache HIT) | **< 150 ms** production contract on Cloudflare Free (measured ~81–130 ms); < 30 ms remains an aspirational figure requiring Argo/Tiered Cache or a plan upgrade — see [BIT-28133](/BIT/issues/BIT-28133) | Cloudflare edge cache |
| TTFB (cache MISS, cached bridge) | < 200 ms | Redis in bridge |
| TTFB (cold, WP fetch) | < 800 ms | Bridge normalizes quickly; WP is internal |
| LCP | < 2.5 s | SSR HTML, preload hero image, no hydration waterfall |
| CLS | < 0.1 | Reserve image dimensions, no layout-shifting ads on load |
| FID / INP | < 200 ms | Near-zero JS, islands only for interactive elements |
| Lighthouse Performance Score | ≥ 90 | SSR + minimal JS + image optimization |
### Image Optimization
- Astro's `<Image />` component: automatic WebP conversion, `width`/`height` attributes prevent CLS
- Cloudflare Image Resizing or self-hosted `sharp` proxy for thumbnails
- `loading="lazy"` on below-the-fold images; `fetchpriority="high"` on hero
---
## 7. Caching Strategy
### Layers
| Layer | Technology | TTL | Scope |
|-------|-----------|-----|-------|
| CDN edge | Cloudflare | 60 s (s-maxage) + 300 s SWR | Full HTML pages, static assets |
| Bridge response cache | Redis | 60 s articles, 300 s categories | WP REST API responses |
| Astro page cache | In-process Map (optional) | 10 s | Repeated SSR renders for same page |
| HTTP Cache-Control | `s-maxage` + `stale-while-revalidate` | Set per route | Instructs CDN |
### Cache Keys
Bridge uses composite keys:
```
posts:{domain}:{slug} → single article
posts-list:{domain}:{category}:{page} → category listing
categories:{domain} → navigation menu
sitemap:{domain} → sitemap data
```
### Invalidation Triggers
1. WordPress `save_post` hook → Bridge `/cache/invalidate` endpoint
2. WordPress `delete_post` hook → Bridge `/cache/invalidate` + Cloudflare purge
3. Manual: `POST /cache/invalidate-all?domain=newsproject.bitreport.pt`
---
## 8. Repository Structure
```
news-platform/
├── frontend/ # Astro 5 SSR application
│ ├── src/
│ │ ├── pages/
│ │ │ ├── index.astro
│ │ │ ├── [category]/
│ │ │ │ ├── index.astro
│ │ │ │ └── [slug].astro
│ │ │ ├── sitemap.xml.ts
│ │ │ └── robots.txt.ts
│ │ ├── components/
│ │ │ ├── layout/
│ │ │ ├── article/
│ │ │ └── islands/ # Client-side interactive islands
│ │ ├── lib/
│ │ │ ├── domain.ts
│ │ │ └── bridge.ts
│ │ └── styles/
│ ├── astro.config.mjs
│ └── package.json
│
├── bridge/ # Fastify bridge API
│ ├── src/
│ │ ├── routes/
│ │ ├── services/
│ │ │ ├── wordpress.ts
│ │ │ └── cache.ts
│ │ └── normalizers/
│ │ └── post.ts
│ ├── package.json
│ └── tsconfig.json
│
├── wordpress/ # WP config and custom plugins
│ ├── plugins/
│ │ └── bridge-invalidator/
│ └── docker-compose.yml
│
├── config/
│ └── domains/
│ └── newsproject.bitreport.pt.json
│
├── deploy/
│ ├── nginx/
│ │ └── newsproject.conf
│ └── lxc/
│ └── setup.sh
│
└── docs/
├── architecture.md # This file
├── frontend.md
├── bridge.md
├── domains.md
├── seo.md
└── deployment.md
```
---
## 9. Infrastructure Overview
See [docs/deployment.md](./deployment.md) for full LXC setup.
- **LXC container:** `news-project-test` on Proxmox, Ubuntu 24.04
- **CPU:** 2 cores, **RAM:** 4 GB, **Disk:** 20 GB
- **Domain:** `newsproject.bitreport.pt` (NPM configured by user)
- **Services:** Nginx, Node.js (Astro + Fastify), WordPress (Docker), Redis, MySQL
---
## 10. Future Scalability
The current architecture supports future growth without structural changes:
| Future requirement | How it is supported |
|-------------------|---------------------|
| Multiple domains | Add `config/domains/<host>.json` — no code change |
| Multiple WordPress instances | Bridge routes by domain → different `wp_endpoint` per config |
| Horizontal frontend scaling | Astro is stateless SSR — add nodes behind Nginx upstream |
| CDN multi-region | Cloudflare global edge already handles it |
| Multi-language | `locale` field in domain config; i18n routes (`/en/`, `/pt/`) per domain |
| Ad network integration | Islands architecture: drop ad island component per placement |
| Multi-theme | `theme` field in domain config; Astro layout resolves theme component set |
| AMP | Optional: Astro can render AMP-compliant output per route (`/amp/[slug]`) |