1. Problem and scope
ekanatha.io is a personal long-form publishing platform. The previous generation was an ASP.NET Core 10 API, a Next.js 15 frontend, PostgreSQL and Redis, deployed as four Railway services. It worked, but for a single-author site it carried the operating cost of a multi-team system: two languages, two deploy pipelines, an HTML-only content format and a Railway-specific network topology.
This generation keeps every user-facing capability and collapses the runtime into one TypeScript service plus a database.
Functional requirements
- Publish long-form articles grouped into categories (topics). Each article targets an 8–15+ minute read (roughly 1,850–3,500+ words at 230 wpm).
- Store and render content as Markdown, exactly as written: GFM tables, task lists, footnotes, code with syntax highlighting, and Mermaid for HLDs, LLDs, sequence diagrams, flowcharts, state machines and ER diagrams.
- A Word-style editor: ribbon toolbar (Home, Insert, Diagrams, Style, AI), live preview identical to the public page, per-article style settings (typeface, size, line height, measure, drop cap, justification).
- An AI editor: generate a full article from a topic, revise through chat, and rewrite a selection (improve, shorten, expand, tabulate, diagram).
- An auto-posting job: publish scheduled articles on time, and once a day turn the next queued topic into an article.
- Multiple colourful reader themes inspired by warm editorial palettes (cream, sage, clay, lavender, midnight).
- Import and export
.mdfiles with front matter.
Non-functional requirements
| Concern | Target | Notes |
|---|---|---|
| Availability | Single VPS, restart-on-failure | Personal site; no multi-region requirement |
| Read latency (p95) | < 300 ms TTFB | Server-rendered, Postgres on the same host |
| Write volume | < 50 writes/day | One author plus the scheduler |
| Storage | < 5 GB in year one | Text plus uploaded images on a volume |
| Security | Single admin, no public write paths | Session cookie, rate-limited login |
| Portability | Any Docker host | Compose file is the deployment contract |
2. High-level design (HLD)
flowchart LR
reader["Reader browser"] -->|HTTPS| caddy["Caddy reverse proxy"]
admin["Admin browser"] -->|HTTPS| caddy
caddy --> web["Next.js 16 app (Node 22)"]
scheduler["Scheduler container"] -->|"POST /api/jobs/tick"| web
web -->|SQL| pg[("PostgreSQL 17")]
web -->|"chat completions"| openai["OpenAI API"]
web --> uploads[("Uploads volume")]The system has three containers and one external dependency:
- web — Next.js App Router. Public pages are server components; the admin studio is a client application talking to JSON route handlers under
/api/admin/*. - scheduler — a 30-line Node script that calls the tick endpoint every minute with a shared secret. All business logic stays in
web; the scheduler only supplies a clock. - postgres — source of truth for categories, articles, versions, the topic queue, media metadata and job state.
- OpenAI — used for generation and revision only, never on the read path.
Why one service instead of API + frontend
| Option | Pros | Cons | Verdict |
|---|---|---|---|
| .NET API + Next.js (previous) | Strong typing in both halves, clean layering | Two runtimes, two images, CORS and token plumbing | Over-built for one author |
| Next.js + separate Node API | Familiar split | Still two deployables and a network hop | No real benefit |
| Next.js full-stack | One language, one image, no CORS, server components read the DB directly | Admin API is coupled to the web app | Chosen |
3. Data model
erDiagram
CATEGORIES ||--o{ ARTICLES : groups
CATEGORIES ||--o{ TOPICS : queues
ARTICLES ||--o{ ARTICLE_VERSIONS : snapshots
TOPICS |o--o| ARTICLES : produces
CATEGORIES {
uuid id PK
text slug UK
text name
text tint
int position
}
ARTICLES {
uuid id PK
text slug UK
text title
text content_md
uuid category_id FK
text status
timestamptz publish_at
int read_minutes
jsonb style
tsvector search
}
ARTICLE_VERSIONS {
uuid id PK
uuid article_id FK
int version
text content_md
}
TOPICS {
uuid id PK
uuid category_id FK
text title
text kind
text status
uuid article_id FK
}Key decisions:
content_mdis canonical. HTML is derived at render time by one pipeline, so the editor preview and the public page can never drift.searchis a generatedtsvectorover title (weight A), excerpt (B) and body (C) with a GIN index — full-text search without a search service.styleisjsonbholding typography settings. It is validated with Zod on write and mapped to a fixed set of CSS variables on read; no user CSS reaches the page.statusis one ofdraft,scheduled,published,archived. Ascheduledrow must havepublish_at.
CREATE TABLE articles (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
slug text NOT NULL UNIQUE,
title text NOT NULL,
excerpt text NOT NULL DEFAULT '',
content_md text NOT NULL DEFAULT '',
category_id uuid REFERENCES categories(id) ON DELETE SET NULL,
status text NOT NULL DEFAULT 'draft',
publish_at timestamptz,
published_at timestamptz,
read_minutes integer NOT NULL DEFAULT 1,
style jsonb NOT NULL DEFAULT '{}',
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', title), 'A') ||
setweight(to_tsvector('english', excerpt), 'B') ||
setweight(to_tsvector('english', content_md), 'C')) STORED
);
CREATE INDEX articles_search_idx ON articles USING gin (search);
4. API contract
| Method | Route | Auth | Purpose |
|---|---|---|---|
POST | /api/auth/login | Public, rate-limited | Exchange email + password for a session cookie |
POST | /api/auth/logout | Session | Clear the session |
GET/POST | /api/admin/articles | Session | List / create articles |
GET/PUT/DELETE | /api/admin/articles/:id | Session | Read / update (snapshots a version) / delete |
POST | /api/admin/preview | Session | Render Markdown with the public pipeline |
POST | /api/admin/ai/generate | Session | Stream a full article for a topic |
POST | /api/admin/ai/revise | Session | Stream a revised article from a chat instruction |
POST | /api/admin/ai/rewrite | Session | Stream a rewrite of the selected text |
GET/POST/PUT/DELETE | /api/admin/categories, /api/admin/topics | Session | Manage taxonomy and topic queue |
GET/PUT | /api/admin/automation | Session | Auto-post settings and last run |
POST | /api/admin/media | Session | Upload an image |
POST | /api/admin/import | Session | Import .md files with front matter |
POST | /api/jobs/tick | Bearer CRON_SECRET | Run due work |
GET | /api/health | Public | Liveness + DB readiness |
5. Low-level design (LLD)
classDiagram
class MarkdownRenderer {
+renderMarkdown(md) RenderResult
-mermaidBlocks() Plugin
-callouts() Plugin
-sanitizeSchema Schema
}
class RenderResult {
+html string
+headings Heading[]
}
class ArticleRepository {
+listPublished(opts) ArticleCard[]
+getPublishedBySlug(slug) Article
+save(input) Article
+snapshotVersion(id)
}
class AiWriter {
+streamArticle(topic, category, kind) Stream
+streamRevision(markdown, chat) Stream
+streamRewrite(selection, action) Stream
}
class AutoPoster {
+tick(now) TickResult
-publishDue(now)
-claimDailyRun(today) bool
-generateNextTopic()
}
MarkdownRenderer --> RenderResult
AutoPoster --> AiWriter
AutoPoster --> ArticleRepositoryThe rendering pipeline
flowchart TD md["Markdown source"] --> parse["remark-parse + remark-gfm"] parse --> rehype["remark-rehype (allow raw HTML)"] rehype --> raw["rehype-raw"] raw --> sanitize["rehype-sanitize (allow-listed tags and classes)"] sanitize --> mermaid["mermaid plugin: code.language-mermaid to figure"] mermaid --> callout["callout plugin: GitHub alerts"] callout --> slug["rehype-slug + autolink headings"] slug --> shiki["Shiki dual-theme highlighting"] shiki --> html["HTML + heading outline"]
Sanitizing before highlighting matters: Shiki emits inline style attributes for token colours, which the sanitizer would otherwise strip. Author-supplied HTML never gets style — formatting such as text colour, size and alignment uses an allow-listed class vocabulary (tc-plum, fs-lg, align-center), which keeps every theme in control of the actual colours.
const schema = {
...defaultSchema,
tagNames: [...defaultSchema.tagNames!, "mark", "u", "figure", "figcaption", "details", "summary"],
attributes: {
...defaultSchema.attributes,
span: [["className", ...TEXT_CLASSES]],
p: [["className", ...BLOCK_CLASSES]],
code: [["className", /^language-[\w-]+$/]],
},
};
Notice that className values are matched against a list or a pattern; anything else is dropped.
6. Key flows
Publishing from the editor
sequenceDiagram
actor Author
participant Editor as Editor (client)
participant API as /api/admin/articles/:id
participant DB as PostgreSQL
Author->>Editor: Type Markdown, use ribbon
Editor->>API: POST /api/admin/preview (debounced)
API-->>Editor: Rendered HTML (same pipeline as public)
Author->>Editor: Click Publish
Editor->>API: PUT article {status: published}
API->>DB: INSERT article_versions (snapshot)
API->>DB: UPDATE articles SET read_minutes, published_at
API-->>Editor: 200 ArticleAI generation with streaming
sequenceDiagram
actor Author
participant Editor
participant Route as /api/admin/ai/generate
participant OpenAI
Author->>Editor: Topic + category + format
Editor->>Route: POST {topic, kind}
Route->>OpenAI: chat.completions (stream)
loop tokens
OpenAI-->>Route: delta
Route-->>Editor: text chunk
Editor->>Editor: append to document
end
Editor->>Editor: parse front matter into title, excerpt, tagsStreaming removes the "request timed out after 30 s" failure mode of the previous design, where revisions had to run as background jobs that the UI polled.
7. The auto-posting job
stateDiagram-v2 [*] --> pending: topic queued pending --> generating: daily run claims it generating --> done: article saved generating --> failed: model or validation error failed --> pending: author retries done --> [*]
flowchart TD
tick["Scheduler: POST /api/jobs/tick"] --> due{"Scheduled articles due?"}
due -->|yes| pub["Publish them"]
due -->|no| ai
pub --> ai{"AI enabled and past run hour?"}
ai -->|no| stop["Return"]
ai -->|yes| claim{"Atomic claim of today's run"}
claim -->|"0 rows"| stop
claim -->|"1 row"| next["Take next pending topic"]
next --> gen["Generate article"]
gen --> len{"Read time at least 8 min?"}
len -->|no| expand["One expansion pass"]
len -->|yes| save
expand --> save["Save as published or draft"]The daily claim is a single conditional UPDATE … WHERE last_run_date < $today RETURNING id. Two concurrent ticks — or a restart mid-run — can never post twice or bill twice.
const claimed = await db
.update(settings)
.set({ lastRunDate: today, lastRunStatus: "running" })
.where(and(eq(settings.id, "ai"), or(isNull(settings.lastRunDate), lt(settings.lastRunDate, today))))
.returning({ id: settings.id });
if (claimed.length === 0) return { skipped: "already ran today" };
8. Security, failure modes and observability
- Auth: one admin, bcrypt password hash in the environment, an HS256 session JWT in an
HttpOnly; Secure; SameSite=Laxcookie, and an in-memory login limiter (5 attempts per 15 minutes per IP).proxy.tsredirects unauthenticated/admintraffic; every admin route handler verifies the session again. - Content: sanitised on render; Mermaid runs with
securityLevel: "strict"; uploads accept only JPEG, PNG, WebP and GIF up to 10 MB, with server-generated filenames. - Secrets:
OPENAI_API_KEY,SESSION_SECRETandCRON_SECRETcome from the environment, never the database. - OpenAI down: the run is marked
failedwith the error, the topic returns tofailed, and the author can retry from the queue. Reads are unaffected. - Database down:
/api/healthreturns 503; Docker restarts the container; Caddy keeps TLS up. - Observability: structured JSON logs from the tick endpoint and AI routes;
docker compose logson the VPS.
9. Deployment
| Environment | Runtime | Command |
|---|---|---|
| Local development | Node 22 + Postgres in Podman | podman compose up -d db && npm run dev |
| Local container test | Podman | podman compose up --build |
| Production | Hostinger VPS, Docker | docker compose -f compose.yaml -f compose.prod.yaml up -d --build |
Migrations are additive SQL files generated by Drizzle Kit and applied on start-up by the app's instrumentation hook, so a fresh VPS needs only docker compose up.
10. Decisions log
| # | Decision | Alternatives | Reason |
|---|---|---|---|
| 1 | Markdown as the stored format | TipTap JSON, HTML | Portable, diffable, AI-native, renders "as is" |
| 2 | Request-time rendering (cacheComponents off) | Cache Components + use cache | Build must not need a database; revisit with use cache + cacheTag when traffic justifies it |
| 3 | Drizzle + pg | Prisma | No engine binary in the image, SQL-shaped queries |
| 4 | Scheduler as a separate container | In-process timers | Survives hot reloads and keeps the clock outside the web process |
| 5 | Classes, not inline styles, for formatting | style attribute | Theme-safe and XSS-safe |
| 6 | Caddy for TLS | Nginx + certbot | Automatic HTTPS with a three-line config |
11. Implementation plan
- Foundation — schema, migrations, renderer, health check. Exit:
/api/healthis green in Podman. - Public site — home, categories, article, search, RSS, sitemap, themes. Exit: the seed article renders every diagram type.
- Studio — login, article table, ribbon editor, live preview, versions, import/export. Exit: an article goes draft → scheduled → published.
- AI — generate, revise, rewrite, topic queue. Exit: a queued topic becomes a 2,000+ word draft.
- Automation and deploy — tick endpoint, scheduler, Caddy, Hostinger runbook. Exit: production publishes on schedule with HTTPS.