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.
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.
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.
| 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
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.
What Is Written in That One Transaction
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.
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.v1content.notification.feature-updates.v1content.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.
Deep Dive 2 — Search Architecture
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 |
|---|---|
k8s | Kubernetes |
spring async event | event-driven architecture |
vector search | pgvector |
system design outbox | transactional outbox pattern |
kub | Kubernetes |
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
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
One Run as a State Machine
| 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
Every Tool Is a Typed Contract
| 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
UPDATEwith 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
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.
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
Recipient State Machine
Each recipient row is its own small state machine, so one bad address never blocks the rest of the batch.
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.
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
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
| 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.
Repository Wiki
Explore the architecture and implementation with source-linked repository documentation.
- Portfolio front end
- AI orchestration and MCP gateway
- Public and admin MCP server
- Content management, search and RAG indexing
- Subscriptions and notification delivery
- Visitor analytics
- Application Copilot
AI-generated repository documentation; it may lag behind the code. Devin sign-in and workspace access may be required.



Comments