Portfolio Platform

Year2026
TechnologyNext.js, TypeScript, Spring Boot, Kafka, PostgreSQL, pgvector, OpenSearch, Valkey, Gemini, OpenAI, MCP, Google Cloud Run, Vercel, Flyway, 微服务架构, AI 助手, 事件驱动, 可观测性
Project

Portfolio Platform demo

Portfolio Platform video cover
0:00 / 0:19Home

Production Architecture Case Study · 2026

Production-Grade Event-Driven Microservice Architecture

A full-stack portfolio platform designed as a real distributed system: event-driven content publishing, Kafka fan-out, OpenSearch indexing, RAG-powered AI assistant, privacy-aware analytics, and reliable notification delivery.

Transactional Outbox Kafka Fan-Out Idempotent Consumers Leases + Fencing Derived Projections RAG MCP Tool Governance Retry Backoff DLQ Graceful Degradation

Start Here — a Map You Can Click

The platform is five systems that share one event backbone. Explore the steps below to follow the workflow; every deep dive has a UML diagram of the real flow and a link to try that flow on the live site.

flowchart TB Admin("Admin + MCP") Content[("Content store")] Kafka(["Kafka"]) Search("Search") AI("AI assistant") Media("Media pipeline") Notify("Notifications") GitHub("Open Source evidence") Web("Website") Analytics("Analytics + monitoring") Admin -->|"write"| Content Content -->|"outbox"| Kafka Kafka --> Search Kafka --> AI Kafka --> Media Kafka --> Notify Search --> Web AI --> Web Media --> Web Content -->|"read"| Web GitHub --> Web Web -->|"events"| Analytics Analytics -->|"alerts"| Notify
Portfolio Platform: complete capability map

② Publishing Search ① Ask AI ⑤ MCP ④ Analytics ③ Notifications Reliability Consistency Deployment

Try the System While You Read

Nothing below is a mock-up. Each row is a live entry point into the same services this article describes.

Do this What happens behind it Read about it
Open the chat in the corner and ask Mr. Pot “How does publishing work here?” Budget reservation, guardrails, pgvector retrieval, a streamed answer with sources ① Ask AI
Press ` or ⌘K and run mcp call search_portfolio kafka A real JSON-RPC tools/call against the public MCP server ⑤ MCP
Run the MCP playground Fixed, read-only tool calls with the request and result shown side by side ⑤ MCP
Spin the visitor globe Your own page view travels edge → Kafka → rollups and comes back as an aggregated, city-level pin ④ Analytics
Step through a UML sequence diagram Message-by-message walkthrough of all five workflows, with alt / loop / critical fragments ② Publishing
In the terminal, run kubectl get pods and git log Live Cloud Run service status (scale-to-zero indexers included) and the platform's decision history Deployment

1. Executive Summary

This project is not a traditional static portfolio website. It is a production-grade distributed platform built around event-driven microservices, AI-assisted user interaction, real-time analytics, search indexing, notification delivery, and reliable asynchronous processing.

The portfolio website is only the user-facing surface. Behind it is a backend platform designed around the same engineering concerns found in real production systems:

  • Reliable content propagation through Kafka using the Transactional Outbox Pattern, with leased, fenced relays.
  • Search indexing through OpenSearch BM25 with index-time document expansion, so queries never pay for an LLM call.
  • AI orchestration through an Agent Service, RAG over pgvector, a daily model budget, and MCP-based tool governance.
  • Analytics processing through an idempotent event pipeline with deduplication and privacy-aware aggregation.
  • Email notification delivery through a state-machine-based dispatcher with leases, retry, backoff, and failure isolation.

Architecture thesis. The platform separates the source of truth from derived projections. PostgreSQL owns canonical content. Kafka distributes change events. OpenSearch, pgvector, analytics rollups, and notification state are independently maintained projections that can be rebuilt, replayed, or repaired without corrupting the core content model.

The architecture prioritizes reliability, loose coupling, graceful degradation, observability, cost efficiency, and clear service ownership.


2. Product Context — Who Uses What

Four kinds of actors use the platform. The use-case view below shows which capability each one touches; the numbers match the five systems on the map.

flowchart LR Visitor(["Visitor / recruiter"]) Subscriber(["Subscriber"]) Owner(["Site owner"]) Client(["AI client<br/>Claude · Codex"]) subgraph Platform["Portfolio Platform"] direction TB UC1(["Browse projects, blogs, CV"]) UC2(["Search content"]) UC3(["① Ask Mr. Pot"]) UC4(["④ See live visitor stats"]) UC5(["③ Get update emails"]) UC6(["② Write and publish"]) UC7(["④ Review visitors and alerts"]) UC8(["⑤ Call typed tools"]) end Visitor --> UC1 Visitor --> UC2 Visitor --> UC3 Visitor --> UC4 Subscriber --> UC5 Owner --> UC6 Owner --> UC7 Owner --> UC8 Client --> UC8
Capability What it does
Portfolio browsing Visitors read projects, blogs, technical articles, life stories, and resume content. Lists are server-rendered so crawlers and no-JS clients see them.
Admin content management The site owner creates, updates, publishes, rolls back, and archives content through an admin console or MCP tools.
Search Natural phrases, abbreviations, typos, and related technical concepts all find the right article.
AI chat assistant “Mr. Pot” answers questions from the portfolio's own content with sources, and reaches backend capabilities only through a governed tool gateway.
Analytics and notifications The platform counts visits once, aggregates them for dashboards and the visitor globe, and emails subscribers when content is published.

3. Architecture at a Glance

Area Design Choice Why It Matters
Write Path Content Service + PostgreSQL + Outbox Protects the canonical content model from downstream failures.
Event Backbone Kafka Decouples content publishing from indexing, RAG, and notifications; decouples page tracking from aggregation.
Search OpenSearch BM25 + generated search terms Improves recall without paying LLM cost at query time.
AI Agent Service + RAG + MCP Gateway Separates reasoning from execution and prevents unsafe direct backend mutation.
Analytics Kafka + Redis SETNX + durable inbox + PostgreSQL rollups At-least-once ingestion, counted exactly once in effect.
Notifications Recipient state machine + leased dispatcher Safe retry, per-recipient failure isolation, and no double sends.

Container View — the Whole Platform on One Page

Portfolio Platform system architecture: a map of how Ask AI, content publishing, notifications, visitor analytics and the MCP tools connect, then one lane per system from the Next.js UI and its Vercel API routes to Cloud Run services, their data stores and Kafka topics
System architecture. One lane per system, from the Next.js UI to Cloud Run services, data stores and Kafka topics. The diagram is generated from the same topology files the repository checks in CI. Open the interactive explorer →

Architecture principle. Each capability sits behind an independently deployable service. Services talk through Kafka when eventual consistency is acceptable, and through synchronous APIs only when a user-facing request needs an immediate answer. One slow or failing downstream system cannot break publishing.


4. Service Ownership and Boundaries

Service Responsibility Owns Data? Communication Style
Frontend (Next.js) Portfolio UI, admin UI, chat widget, API routes, tracking edge No HTTP, Kafka producer
Content Service Content CRUD, publishing workflow, versioning, outbox and indexing jobs Yes HTTP + Kafka
Search Indexer Converts content events into OpenSearch documents No Kafka consumer
RAG Indexer Chunks and embeds content into pgvector for AI retrieval No Kafka consumer
Agent Runtime + Knowledge Service Guardrails, intent routing, retrieval, streamed generation, run telemetry Yes HTTP (SSE) + MCP
MCP Tool Gateway Tool registry, RBAC, risk gating, idempotency, audit logging Yes HTTP
Visitor Analytics Event ingestion, deduplication, sessions, rollups, alert rules Yes Kafka consumer + HTTP
Notification Service Subscriber matching, email dispatch, retry lifecycle Yes Kafka consumer + scheduler

Design insight: avoid shared database coupling. Downstream services never mutate the Content Service's core tables. The Content Service owns canonical content; search, RAG, and notifications consume events and build their own projections. That keeps the system evolvable and makes derived data rebuildable.

Non-Functional Requirements

Requirement Design Response
Reliability Transactional outbox, leased retries, dead-letter states, idempotent consumers
Scalability Kafka fan-out, independent consumers, stateless services
Low Latency Cached reads with ETags, async indexing, streaming AI responses
Cost Efficiency Index-time LLM enrichment, zero query-time LLM search, scale-to-zero services, a daily AI budget
Consistency Strong local consistency for writes, eventual consistency for derived projections
Failure Isolation Search, RAG, notification, and analytics fail independently
Observability Structured logs, event IDs, audit trails, per-row retry state, operation timelines
Privacy HMAC-hashed IPs, city-level geo, aggregate-only public views

Deep Dive 1 — Content Publishing Pipeline ②

The Problem

When the owner publishes a project or blog, several systems must react: search must update its document, RAG must regenerate embeddings, and subscribers may need an email. Calling them synchronously inside the publish request is fragile:

  • If Search is unavailable, publishing fails.
  • If Notification is slow, the admin request is slow.
  • If the database commit succeeds but the Kafka publish fails, downstream systems miss the event.
  • If Kafka publishes but the transaction rolls back, consumers process a phantom event.

The system needs reliable event propagation without distributed transactions.

The Solution — a Transactional Outbox, Leased and Fenced

Publishing writes the new version, its outbox event, two indexing jobs and an audit row in one PostgreSQL transaction. There is no dual write to Kafka. Relays then replay rows until Kafka acknowledges them.

sequenceDiagram autonumber actor Operator participant Content as Content Service participant DB as PostgreSQL participant Kafka participant Workers as Index Workers participant Notify as Notifications Operator->>Content: publish(id, version) · JWT, owner role critical one PostgreSQL transaction Content->>DB: INSERT version snapshot Content->>DB: INSERT outbox event Content->>DB: INSERT search + RAG jobs Content->>DB: INSERT audit row end Content-->>Operator: 200 published loop relay every 10 s · leased jobs Content->>DB: claim ready rows · FOR UPDATE SKIP LOCKED Content-)Kafka: publish index event · key = type:id Content->>Workers: POST /drain/{jobId} · wakes the consumer end par search projection Kafka-)Workers: content.search.index.v1 Workers->>Workers: idempotent upsert into OpenSearch and RAG projection Kafka-)Workers: content.rag.index.v1 Workers->>Workers: chunk + embed, replace pgvector chunks and subscriber fan-out Kafka-)Notify: content.notification.* end
Publishing pipeline

▶ Step through this flow message by message

What Is Written in That One Transaction

classDiagram direction LR class ContentVersion { +UUID id +String sourceType +String sourceIdText +int version +Map snapshot +String changeNote } class ContentEventOutbox { +UUID id +OutboxEventType eventType +String topic +Map payload +OutboxStatus status +int retryCount +Instant nextRetryAt +String idempotencyKey +long version } class IndexingJob { +UUID id +JobType jobType +JobStatus status +int retryCount +Instant nextRetryAt +String idempotencyKey +long version } class AuditLog { +String actor +AuditAction action +Map beforeSnapshot +Map afterSnapshot } class JobType { <<enumeration>> SEARCH_INDEX RAG_INDEX } class JobStatus { <<enumeration>> PENDING PROCESSING DONE FAILED SKIPPED DLQ } ContentVersion "1" --> "1" ContentEventOutbox : notification intent ContentVersion "1" --> "2" IndexingJob : search + RAG ContentVersion "1" --> "1" AuditLog : who changed what IndexingJob --> JobType IndexingJob --> JobStatus

Every row carries a unique idempotencyKey that names the exact work, for example:

RAG_INDEX:PROJECT:7c3715bf-7722-4df5-9e83-5d7e9493ea2c:v8
SEARCH_INDEX:PROJECT:7c3715bf-7722-4df5-9e83-5d7e9493ea2c:v8

The Lifecycle of One Job

A relay does not “send and hope.” It claims rows with FOR UPDATE SKIP LOCKED, takes a lease by pushing next_retry_at into the future, and bumps a version column. A relay that outlives its lease cannot overwrite a newer claim.

stateDiagram-v2 [*] --> PENDING: written in the publish transaction PENDING --> PROCESSING: relay claims the row, lease 300 s PROCESSING --> DONE: consumer confirms the projection PROCESSING --> FAILED: consumer reports an error PROCESSING --> PROCESSING: lease expired, replayed safely FAILED --> PROCESSING: backoff elapsed, 60 s doubling FAILED --> DLQ: 8 attempts used DLQ --> PENDING: operator retries DONE --> [*]

Kafka Topic Design

The platform uses topic-level fan-out instead of one generic content topic because each downstream pipeline has different scaling, replay, and failure-handling needs.

Topic Consumer Purpose Operational Concern
content.search.index.v1 Search Indexer Update the OpenSearch projection Replay for reindexing
content.rag.index.v1 RAG Indexer Chunk, embed, replace pgvector chunks Slower because of external embedding calls
content.notification.article-updates.v1
content.notification.feature-updates.v1
content.notification.job-updates.v1
Notification Service Notify the subscribers of each audience Strict deduplication required

Why This Design Works

  • If the transaction rolls back, no outbox row and no job exist: no phantom downstream work.
  • If the transaction commits, the intent is durable in PostgreSQL until Kafka acknowledges it.
  • If Kafka is temporarily unavailable, the relay retries with backoff.
  • If a consumer sees the same event twice, the idempotency key makes the second one a no-op.
  • The indexers scale to zero; the relay's drain call wakes them, so idle time costs nothing.

Architecture decision. The platform chooses at-least-once delivery + idempotent consumers instead of trying to enforce global exactly-once behavior across PostgreSQL, Kafka, OpenSearch, external AI APIs, and email providers. Reliable delivery with safe retries is more achievable and more debuggable than distributed exactly-once semantics.


The Problem

Portfolio search has to handle more than exact keyword matching. A user may type the left column; the relevant document contains the right one.

User types Document says
k8sKubernetes
spring async eventevent-driven architecture
vector searchpgvector
system design outboxtransactional outbox pattern
kubKubernetes

A basic SQL ILIKE search misses these relationships and offers no ranking, stemming, or relevance tuning.

The Solution — Spend the LLM Once, at Index Time

flowchart LR subgraph Write["Index time — once per publish"] direction LR Topic["content.search.index.v1"] Indexer["Search Indexer"] Expand["LLM document expansion<br/>15–40 search terms"] Doc["OpenSearch document<br/>+ search_terms"] Topic --> Indexer Indexer --> Expand Expand -->|fail-open| Indexer Indexer --> Doc end subgraph Read["Query time — no LLM, no embedding"] direction LR Query["User query"] Fuzzy["best_fields<br/>fuzziness AUTO"] Prefix["phrase_prefix<br/>partial words"] Rank["BM25 ranking"] Results["Ranked results"] Query --> Fuzzy Query --> Prefix Fuzzy --> Rank Prefix --> Rank Rank --> Results end Doc -.->|indexed fields| Rank

Three Layers of Recall

Layer When What it adds
1. BM25 full-text ranking Query time Weighted fields: title^3, summary^2, tags^2, search_terms^1.5, content, category; English analyzer for stemming.
2. Index-time document expansion Publish time A Doc2Query-style step asks an LLM for keywords, synonyms, abbreviations, related technologies and likely question phrasings, and stores them in search_terms.
3. Fuzzy + phrase-prefix matching Query time Typos within two edits still match; partial words such as kub reach “Kubernetes”.

The benefit is cost control. The platform pays one cheap model call per document at indexing time instead of paying for every user query. A search for k8s deployment finds a Kubernetes article because “k8s” was written into search_terms when the article was published, not because anything was called during the search.

Failure Handling — Fail Open

  • If the model is unavailable, the indexer still writes the document, without generated terms.
  • Publishing does not fail, and basic search still works.
  • Search quality may degrade temporarily; a reindex regenerates the terms later.

Insight. Search enrichment is a quality improvement, not a correctness requirement. The source of truth remains PostgreSQL and OpenSearch is a projection, so the right behavior is to index minimally and repair enrichment asynchronously, never to fail publishing.


Deep Dive 3 — Ask AI: a Grounded Answer Inside a Budget ①

The Problem

A public chat assistant on a personal site has three ways to go wrong: it can invent facts about the owner, it can be talked into unsafe output, and it can run up an unbounded model bill. Mr. Pot is designed so that each of these has an explicit stop.

The Flow

sequenceDiagram autonumber actor Visitor participant Edge as Next.js API route participant Agent as Agent Runtime participant Redis participant Knowledge as Knowledge Service participant Vec as pgvector participant LLM as LLM API Visitor->>Edge: POST /api/agent/chat · opens an SSE stream Edge->>Agent: stream(query, identity) Agent->>Redis: reserve daily budget · atomic Lua script break daily budget exhausted Agent-->>Visitor: budget notice, run ends end Agent->>Redis: load recent turns · 30-min sliding TTL Agent->>LLM: input safety check break unsafe input Agent-->>Visitor: safe refusal end Agent->>LLM: plan route (intent) · structured output Agent->>Knowledge: search(query, top 6) alt embedding and store respond Knowledge->>Vec: match_current_knowledge_v2 · cosine, min 0.35 Knowledge-->>Agent: evidence + canonical URLs else any step fails Knowledge-->>Agent: error, no stale fallback Agent->>Agent: answer without evidence, failure logged end Agent->>LLM: grounded generation Agent->>LLM: output safety check loop each chunk Agent-->>Visitor: SSE answer event end Agent->>Agent: INSERT run events into the run outbox
Grounded AI answer

▶ Step through this flow message by message

One Run as a State Machine

stateDiagram-v2 [*] --> Requested: question arrives over SSE Requested --> Guarding: daily budget reserved Requested --> Stopped: daily budget exhausted Guarding --> Retrieving: input is safe, route planned Guarding --> Stopped: unsafe input, refusal sent Retrieving --> Generating: evidence found Retrieving --> Generating: retrieval failed, no evidence Generating --> Validating: draft held back Validating --> Answered: output passes, stream to visitor Validating --> Stopped: output fails validation, draft withheld Answered --> [*] Stopped --> [*]
Risk Control Where
Invented facts Answers are generated from retrieved, public, current evidence with canonical source URLs; without evidence the answer says so. Knowledge Service + pgvector chunks written by publishing
Unsafe input or output Safety checks on both sides; the draft is held until validation passes. Agent Runtime
Unbounded cost The daily model budget is reserved atomically before any model work; when it is used up, the run ends with a notice. Redis
Telemetry slowing answers Run events go through an outbox and are written to the search index in batches, off the request path. Run outbox

Insight. Retrieval is a dependency that is allowed to fail. When the embedding call or the vector store is down, the agent answers without evidence and logs the failure rather than returning an error. It also refuses to serve stale chunks, because a confidently wrong answer about a person is worse than a modest one.


Deep Dive 4 — MCP Tool Governance ⑤

The Problem

The assistant, and external AI clients such as Claude and Codex, should be able to use backend capabilities. Letting a model call backend APIs directly is unsafe:

  • The model calls the wrong endpoint, or retries a mutation and duplicates side effects.
  • The model attempts a high-risk action without confirmation, or bypasses authorization.
  • Internal APIs become reachable through prompt injection or tool misuse.

The AI system must treat the LLM as a reasoning layer, not as a trusted execution layer.

The Flow — One Policy Point

sequenceDiagram autonumber actor Client as MCP client participant Edge as Next.js edge participant Server as MCP Server participant Gateway as Tool Gateway participant Service as Domain service Client->>Edge: POST /mcp · JSON-RPC tools/call Edge->>Server: rewrite to Cloud Run · origin stays hidden Server->>Server: validate envelope + bounds break rate limit exceeded Server-->>Client: JSON-RPC error (429) end Server->>Gateway: invoke(tool, args) Gateway->>Gateway: registry + RBAC + risk level opt mutating tool, /mcp/admin only Gateway-->>Client: confirmation required end Gateway->>Gateway: Idempotency-Key check Gateway->>Service: typed, bounded call Service-->>Gateway: rows Gateway->>Gateway: sanitize result · secrets and internal fields removed Gateway-->>Server: typed result Server-->>Client: tool result
Governed MCP call

▶ Step through this flow ▶ Make a real tool call in the playground

Every Tool Is a Typed Contract

classDiagram direction LR class ToolDefinition { +String name +ToolMode mode +String requiredRole +RiskLevel riskLevel +boolean dryRunSupported +boolean confirmRequired +String confirmationMethod +List~ParameterSpec~ parameters +Endpoint endpoint } class ParameterSpec { +String name +String type +boolean required +Integer minLength +Integer maxLength } class Endpoint { +String target +String method +String path } class ToolMode { <<enumeration>> READ WRITE } class RiskLevel { <<enumeration>> LOW MEDIUM HIGH CRITICAL } class RiskGateValidator { +check(tool, args) Outcome } ToolDefinition "1" *-- "many" ParameterSpec ToolDefinition "1" *-- "1" Endpoint ToolDefinition --> ToolMode ToolDefinition --> RiskLevel RiskGateValidator ..> ToolDefinition : enforces
Tool Mode Risk Minimum role Gate
admin.get_content READ LOW VIEWER Allowed after authorization
admin.update_content WRITE MEDIUM EDITOR Schema-validated, idempotency key required, audited with before / after snapshots
resume.update_draft WRITE HIGH ADMIN Requires _confirmed=true or dryRun=true

Roles are ordered VIEWER → EDITOR → PUBLISHER → ADMIN, and a tool with no registered role is treated as ADMIN-only: deny by default.

Architecture decision. The LLM can reason about what should happen, but the gateway decides what is allowed to happen. Separating intelligence from authority is the key safety boundary for production AI systems. This very article is edited through that gateway: each change lands as one audited UPDATE with a before and after snapshot.


Deep Dive 5 — Real-Time Analytics Pipeline ④

The Problem

The platform tracks visitor activity for page-view counts, content popularity, the 3D visitor globe, traffic trends, and admin dashboards. It has to be reliable, counted once, and privacy-aware: a personal site has no business knowing precisely who or where a visitor is.

The Flow

sequenceDiagram autonumber actor Browser participant Edge as Next.js /api/track participant Kafka participant Agg as Visitor Analytics participant Redis participant DB as PostgreSQL rollups Browser->>Edge: POST /api/track · keepalive beacon break rate limited or consent denied Edge-->>Browser: 429 / 204, dropped end Edge->>Edge: geo-snap to city · eventId = UUIDv7 alt Kafka accepts Edge-)Kafka: produce raw event · key = eventId else produce fails Edge->>Edge: fallback, direct PostgreSQL insert with the same eventId end Edge-->>Browser: 200 accepted Kafka-)Agg: poll batch of up to 100 · manual ack loop each record Agg->>Redis: SETNX eventId · duplicates dropped end critical one PostgreSQL transaction Agg->>DB: claim events in the durable inbox Agg->>DB: upsert sessions + 5-min / daily rollups end Agg->>Kafka: ack after commit · on failure, seek + retry Browser->>Edge: GET /api/analytics/visits/summary · CDN caches 60 s Edge->>Agg: GET /visits/summary · If-None-Match alt ETag matches Agg-->>Edge: 304 Not Modified else data changed Agg-->>Edge: 200 + weak ETag end Edge-->>Browser: proxied response
Visitor event pipeline

▶ Step through this flow ▶ See the result on the live globe

Counting Once — Two Gates, Not One

Kafka delivers at least once, so the same event can arrive twice. A cache key alone is not enough, because a cache can be flushed. The aggregator therefore uses a fast gate and a durable gate.

flowchart TD Event["Consume analytics event"] Parse{"Parseable?"} DLQ["Dead-letter to<br/>analytics.events.dlq"] Fast{"Redis SETNX eventId<br/>new?"} Skip["Skip duplicate"] Inbox{"Durable inbox claim<br/>in PostgreSQL, new?"} Upsert["Upsert sessions and rollups<br/>same transaction"] Ack["Ack Kafka offset after commit"] Event --> Parse Parse -- No --> DLQ --> Ack Parse -- Yes --> Fast Fast -- No --> Skip --> Ack Fast -- Yes --> Inbox Inbox -- No --> Skip Inbox -- Yes --> Upsert --> Ack

Privacy Design

Data Strategy Reason
IP address HMAC-SHA256 hash for everything downstream; the raw value is confined to a short-lived private tier Approximate uniqueness without carrying raw IPs through sessions, rollups, or dashboards
Location City level from edge headers, coordinates rounded to about 11 km, aggregated per metro area Supports the globe without pointing at a street
User identity No persistent identity required for public visitors Avoids unnecessary tracking
Event ID UUIDv7 assigned at the edge Time-sortable, and doubles as the de-duplication key on both the Kafka and the fallback path
Aggregation 5-minute and daily rollups over raw detail Fast dashboard queries and less sensitive data retained

Graceful Degradation

  • Preferred path: Kafka ingestion.
  • Fallback path: a direct database insert carrying the same event ID, so a later replay cannot double count.
  • Worst case: analytics quality degrades, but portfolio browsing is unaffected.

Insight. Analytics is important, but it is not on the critical user path. The platform preserves the visitor experience even when analytics infrastructure is degraded: product availability is deliberately ranked above perfect telemetry completeness.


Deep Dive 6 — Notification Service ③

The Problem

When content is published, subscribers may need an email. The system must handle many subscribers, provider failures, duplicate Kafka events, per-recipient retry, and failure isolation. A single Kafka event must not send all emails synchronously; that would make the pipeline slow and fragile.

The Flow — Fan Out First, Send Later

sequenceDiagram autonumber participant Kafka participant Notify as Notifications participant Ledger as Delivery ledger (PostgreSQL) participant SMTP as Email (SMTP) Kafka-)Notify: notification intent · emitted by the outbox relay alt unparseable or invalid Notify-)Kafka: send to DLQ, commit offset else idempotency key already DONE Notify->>Notify: skip duplicate · redelivery is a no-op else new event critical one PostgreSQL transaction Notify->>Ledger: INSERT audit row · idempotency_key UNIQUE Notify->>Ledger: fan out recipient rows · active subscribers + preferences end Notify->>Kafka: commit offset · on DB error, no commit and Kafka redelivers end loop dispatcher tick Notify->>Ledger: claim up to 20 EMAIL rows · FOR UPDATE SKIP LOCKED, lease 10 min loop each claimed recipient Notify->>SMTP: send · Idempotency-Key alt accepted Notify->>Ledger: status = SENT else provider error Notify->>Ledger: retry_count + 1 · rescheduled, max 5 attempts end end end
Notification delivery

▶ Step through this flow message by message

Recipient State Machine

Each recipient row is its own small state machine, so one bad address never blocks the rest of the batch.

stateDiagram-v2 [*] --> PENDING: fan-out inserts the row PENDING --> SENDING: dispatcher claims it, lease 10 min SENDING --> SENT: provider accepts SENDING --> FAILED: provider error, backoff scheduled FAILED --> SENDING: backoff elapsed SENDING --> UNKNOWN: lease expired mid-send PENDING --> SKIPPED: subscriber no longer active SENT --> READ: marked read in the site inbox FAILED --> [*]: 5 attempts used UNKNOWN --> [*]: verify before any retry SKIPPED --> [*] READ --> [*]

Claiming a Batch

WITH picked AS (
    SELECT id
      FROM notification_recipients
     WHERE channel = 'EMAIL'
       AND status IN ('PENDING', 'FAILED')
       AND (next_retry_at IS NULL OR next_retry_at <= now())
       AND retry_count < 5
     ORDER BY created_at
     LIMIT 20
       FOR UPDATE SKIP LOCKED
)
UPDATE notification_recipients r
   SET next_retry_at = now() + interval '10 minutes'   -- the lease
  FROM picked
 WHERE r.id = picked.id
RETURNING r.*;

Multiple workers can run in parallel without sending the same email twice. Every later status update is conditional on the lease the worker was given, so a worker that lost its lease cannot mark a row.

Backoff Policy

After failure 1st 2nd 3rd 4th 5th
Next attempt in 60 s 120 s 240 s 480 s none: stays FAILED, inspectable and replayable by an operator

Insight: the honest state is UNKNOWN. If a worker dies after handing a message to the provider but before recording the result, nobody knows whether the email left. Retrying blindly risks a duplicate; marking it sent risks a silent loss. The row is parked as UNKNOWN until delivery is verified. That is “at most once per recipient” taken seriously.


Deep Dive 7 — Reliability and Failure Handling

End-to-End Delivery Semantics

The system uses at-least-once messaging with idempotent side effects, which is more practical than global exactly-once behavior across databases, Kafka, APIs, and third-party providers.

flowchart LR Producer["Producer"] Outbox["Transactional outbox<br/>durable intent"] Relay["Leased relay<br/>retry + backoff"] Kafka["Kafka<br/>at-least-once"] Consumer["Consumer"] Dedup{"Idempotency<br/>check"} Effect["Side effect<br/>index · email · rollup"] Park["Parked for an operator<br/>DLQ / FAILED / UNKNOWN"] Producer --> Outbox Outbox --> Relay Relay --> Kafka Kafka --> Consumer Consumer --> Dedup Dedup -- new --> Effect Dedup -- seen --> Consumer Relay -. attempts used .-> Park Consumer -. poison event .-> Park

Failure Scenarios

Failure Handling System Behavior
DB transaction rolls back No outbox event is created No phantom downstream work
Kafka publish fails Relay retries with backoff Event remains durable in PostgreSQL
Relay crashes after claiming Lease expires, another relay replays Version bump fences out the stale relay
Consumer crashes before committing its offset Kafka redelivers Idempotency key makes the replay a no-op
Search indexing keeps failing Backoff, then DLQ state after 8 attempts Search projection lags; an operator retries with one tool call
LLM enrichment fails Index without enrichment Search remains functional
Retrieval fails for Ask AI Answer without evidence, failure logged Chat stays available
Email provider fails Retry with exponential backoff Per-recipient retry isolation
Poison event appears Route to a dead-letter topic Pipeline keeps processing healthy events
Kafka unavailable for analytics Direct database insert with the same event ID Visitor experience preserved, no double count later
Daily AI budget used up Run ends with a notice before any model call Cost stays bounded

Two Kinds of Dead Letter

Kind Where it lives Used for
Dead-letter state A DLQ status on the outbox or job row in PostgreSQL Work the platform created and could not complete after 8 attempts. It stays queryable, with its last error, and can be retried or replayed from the admin tools.
Dead-letter topic A Kafka topic such as analytics.events.dlq Records a consumer cannot even parse. They are moved aside so the partition keeps flowing.

Deep Dive 8 — Data Consistency Model

flowchart TB ContentDB[("PostgreSQL<br/>source of truth")] Kafka{{"Kafka events"}} Search[("OpenSearch<br/>search projection")] Vector[("pgvector<br/>RAG projection")] Notify[("Delivery ledger<br/>notification projection")] Ask["① Ask AI reads"] Find["Site search reads"] ContentDB -->|outbox relay| Kafka Kafka --> Search Kafka --> Vector Kafka --> Notify Vector -.-> Ask Search -.-> Find ContentDB -. rebuild / reindex .-> Search ContentDB -. rebuild / reindex .-> Vector

The Content Service database is the source of truth for portfolio content. OpenSearch, pgvector, and notification rows are derived projections, which means they can be rebuilt from source data if needed.

The platform accepts eventual consistency for derived systems:

  • A blog is published immediately.
  • Search updates seconds later.
  • RAG chunks update after embedding.
  • Notifications send asynchronously.

Architecture decision. The publish request never blocks on search indexing, embedding generation, or email delivery. Those are projections and side effects; blocking on them would reduce reliability and increase user-facing latency.


Deep Dive 9 — Deployment Architecture

flowchart TB subgraph Vercel["Vercel"] FE["Next.js UI + API routes"] end subgraph CloudRun["Google Cloud Run — min 0–1, max 1–2 instances, CPU per request"] Content["Content Service"] Agent["Agent Runtime + Knowledge"] Idx["Search + RAG indexers<br/>scale to zero"] Analytics["Visitor Analytics + Alerts"] Notify["Notification Service"] Mcp["MCP Server + Tool Gateway"] end subgraph Data["Managed data infrastructure"] Kafka{{"Kafka"}} OS[("OpenSearch")] Redis[("Redis")] PG[("PostgreSQL + pgvector")] end subgraph External["External APIs"] LLM["LLM API"] Email["Email (SMTP)"] end FE --> Content FE --> Agent FE --> Analytics FE --> Mcp FE --> Kafka Content --> PG Content --> Kafka Idx --> Kafka Idx --> OS Idx --> PG Agent --> PG Agent --> Redis Agent --> LLM Analytics --> Kafka Analytics --> Redis Analytics --> PG Notify --> Kafka Notify --> PG Notify --> Email Mcp --> Content
Concern How it is handled
Delivery GitHub Actions (OIDC) → Cloud Build → Cloud Run for the services; the front end deploys on Vercel, and a CI job verifies the production release.
Database migrations Flyway, version-controlled and shipped with the release rather than applied by hand.
Scale to zero Event-driven indexers sleep until the relay's drain call wakes them.
Kubernetes Not used today. ADR-001: Cloud Run today, Kubernetes as the exit path — spiky, low traffic and one maintainer make scale-to-zero and per-request billing cheaper than an always-on cluster. Every service is an OCI image with health endpoints, so the move to GKE is mapped out for when steady traffic justifies it.

Technology Stack

Layer Technology Purpose
Frontend Next.js, TypeScript, Vercel Portfolio UI, admin dashboard, chat widget, API routes
Backend Spring Boot 3, Java 21 Microservices
Messaging Kafka Event streaming, fan-out, async processing
Database PostgreSQL Content, outbox, notification state, analytics rollups
Vector Search pgvector RAG chunks and embeddings
Search OpenSearch Full-text search, BM25, agent run traces
Cache Redis (Valkey) Deduplication, rate limiting, AI budget, chat memory
AI Gemini, OpenAI Intent routing, chat, enrichment, embeddings
Tooling MCP Controlled AI tool execution
Infrastructure Cloud Run, Vercel, Flyway, GitHub Actions Deployment and migrations

Production Reliability Patterns

Pattern Used In Why It Matters See
Transactional Outbox Content Service Prevents DB/Kafka dual-write inconsistency Deep Dive 1
Lease + Fencing Relays, email dispatcher A stale worker cannot overwrite a newer claim 1, 6
Idempotent Consumer Kafka consumers Makes redelivery safe Deep Dive 7
Dead Letter Outbox, indexing jobs, consumers Isolates poison work without losing it Deep Dive 7
Exponential Backoff Relays, email dispatch Prevents provider overload Deep Dive 6
SETNX + Durable Inbox Analytics Counts each event once, even across a cache flush Deep Dive 5
Source-of-Truth + Projection Search and RAG Enables rebuildable derived data Deep Dive 8
Fail-Open Enrichment Search Indexer LLM failure does not block indexing Deep Dive 2
Graceful Degradation Analytics tracking, Ask AI retrieval A dependency outage lowers quality, not availability 5, 3
Budget Reservation Agent Runtime Bounds model spend before work starts Deep Dive 3
RBAC Tool Gateway + Audit MCP Prevents unsafe backend mutation and makes every tool call traceable Deep Dive 4

Engineering Outcomes

This platform demonstrates several production-level engineering capabilities:

  • Designing event-driven systems with Kafka.
  • Applying the Transactional Outbox pattern correctly, including leases and fencing.
  • Building idempotent consumers and retryable pipelines.
  • Separating source-of-truth data from derived projections.
  • Implementing practical search using BM25 and index-time expansion.
  • Designing safer AI agents with budgets, guardrails, and MCP governance.
  • Building real-time analytics with privacy-aware aggregation.
  • Designing reliable email dispatch with state machines and backoff.
  • Deploying independently scalable services on Cloud Run and managed infrastructure.

The result is a portfolio platform that functions as both a personal website and a living system design showcase: loosely coupled, observable, resilient to partial failure, and organized around clear ownership boundaries.

Core principle. Keep the source of truth simple and reliable, then use events to build scalable, independent projections around it.

↑ Back to the clickable map ▶ Interactive architecture explorer ▶ How the platform evolved


Repository Wiki

Explore the architecture and implementation with source-linked repository documentation.

AI-generated repository documentation; it may lag behind the code. Devin sign-in and workspace access may be required.

Comments

Be kind. Comments are reviewed before appearing.