Skip to content

Designing ekanatha.io: a Markdown-first publishing platform with an AI editor

The HLD, LLD, data model, sequence flows and deployment plan behind ekanatha.io — a single Next.js service with a Word-style Markdown editor, an AI co-writer and an auto-posting job, shipped to a Hostinger VPS with Docker.

Ekanatha Reddy Urivakili8 min1,273 words

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 .md files with front matter.

Non-functional requirements

ConcernTargetNotes
AvailabilitySingle VPS, restart-on-failurePersonal site; no multi-region requirement
Read latency (p95)< 300 ms TTFBServer-rendered, Postgres on the same host
Write volume< 50 writes/dayOne author plus the scheduler
Storage< 5 GB in year oneText plus uploaded images on a volume
SecuritySingle admin, no public write pathsSession cookie, rate-limited login
PortabilityAny Docker hostCompose 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

OptionProsConsVerdict
.NET API + Next.js (previous)Strong typing in both halves, clean layeringTwo runtimes, two images, CORS and token plumbingOver-built for one author
Next.js + separate Node APIFamiliar splitStill two deployables and a network hopNo real benefit
Next.js full-stackOne language, one image, no CORS, server components read the DB directlyAdmin API is coupled to the web appChosen

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:

  1. content_md is canonical. HTML is derived at render time by one pipeline, so the editor preview and the public page can never drift.
  2. search is a generated tsvector over title (weight A), excerpt (B) and body (C) with a GIN index — full-text search without a search service.
  3. style is jsonb holding 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.
  4. status is one of draft, scheduled, published, archived. A scheduled row must have publish_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

MethodRouteAuthPurpose
POST/api/auth/loginPublic, rate-limitedExchange email + password for a session cookie
POST/api/auth/logoutSessionClear the session
GET/POST/api/admin/articlesSessionList / create articles
GET/PUT/DELETE/api/admin/articles/:idSessionRead / update (snapshots a version) / delete
POST/api/admin/previewSessionRender Markdown with the public pipeline
POST/api/admin/ai/generateSessionStream a full article for a topic
POST/api/admin/ai/reviseSessionStream a revised article from a chat instruction
POST/api/admin/ai/rewriteSessionStream a rewrite of the selected text
GET/POST/PUT/DELETE/api/admin/categories, /api/admin/topicsSessionManage taxonomy and topic queue
GET/PUT/api/admin/automationSessionAuto-post settings and last run
POST/api/admin/mediaSessionUpload an image
POST/api/admin/importSessionImport .md files with front matter
POST/api/jobs/tickBearer CRON_SECRETRun due work
GET/api/healthPublicLiveness + 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 --> ArticleRepository

The 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 Article

AI 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, tags

Streaming 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=Lax cookie, and an in-memory login limiter (5 attempts per 15 minutes per IP). proxy.ts redirects unauthenticated /admin traffic; 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_SECRET and CRON_SECRET come from the environment, never the database.
  • OpenAI down: the run is marked failed with the error, the topic returns to failed, and the author can retry from the queue. Reads are unaffected.
  • Database down: /api/health returns 503; Docker restarts the container; Caddy keeps TLS up.
  • Observability: structured JSON logs from the tick endpoint and AI routes; docker compose logs on the VPS.

9. Deployment

EnvironmentRuntimeCommand
Local developmentNode 22 + Postgres in Podmanpodman compose up -d db && npm run dev
Local container testPodmanpodman compose up --build
ProductionHostinger VPS, Dockerdocker 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

#DecisionAlternativesReason
1Markdown as the stored formatTipTap JSON, HTMLPortable, diffable, AI-native, renders "as is"
2Request-time rendering (cacheComponents off)Cache Components + use cacheBuild must not need a database; revisit with use cache + cacheTag when traffic justifies it
3Drizzle + pgPrismaNo engine binary in the image, SQL-shaped queries
4Scheduler as a separate containerIn-process timersSurvives hot reloads and keeps the clock outside the web process
5Classes, not inline styles, for formattingstyle attributeTheme-safe and XSS-safe
6Caddy for TLSNginx + certbotAutomatic HTTPS with a three-line config

11. Implementation plan

  1. Foundation — schema, migrations, renderer, health check. Exit: /api/health is green in Podman.
  2. Public site — home, categories, article, search, RSS, sitemap, themes. Exit: the seed article renders every diagram type.
  3. Studio — login, article table, ribbon editor, live preview, versions, import/export. Exit: an article goes draft → scheduled → published.
  4. AI — generate, revise, rewrite, topic queue. Exit: a queued topic becomes a 2,000+ word draft.
  5. Automation and deploy — tick endpoint, scheduler, Caddy, Hostinger runbook. Exit: production publishes on schedule with HTTPS.